shithub: fsgen

ref: e49f718071886411a94f42ebf007f08eca4cfa9d
dir: /code.c/

View raw version
#include <u.h>
#include <libc.h>
#include "dat.h"
#include "fns.h"

static void
printvars(VFile *file)
{
	char **a;
	char buf[64];
	int n;
	
	for (a = file->parts; *a; a++) {
		if (!(*a)[0])
			continue;
		n = strlen(*a) - 1;
		if (!((*a)[0] == '{' && (*a)[n] == '}'))
			continue;
		strcpy(buf, *a);
		buf[n] = 0;
		print(", char *%s", buf+1);
	}
}

char *invalid = "/{}";

static void
pathtostring(char *buf, int max, char *path)
{
	char *s;
	strncpy(buf, path, max);
	buf[max-1] = 0;
	for (s = buf; *s; s++)
		if (strchr(invalid, *s))
			*s = '_';
}

void
printread(VFile *file)
{
	char buf[64];
	pathtostring(buf, sizeof(buf), file->path);
	print("static void\nfsread_%s(Req *r", buf);
	printvars(file);
	print(")\n");
}

void
printwrite(VFile *file)
{
	char buf[64];
	pathtostring(buf, sizeof(buf), file->path);
	print("static void\nfswrite_%s(Req *r", buf);
	printvars(file);
	print(")\n");
}

void
printls(VFile *file)
{
	char buf[64];
	pathtostring(buf, sizeof(buf), file->path);
	print("static void\nfsls_%s(...)\n", buf);
}

void
printpre()
{
	print("#line 0 \"preamble.inc\"\n"
#include "preamble.cinc"
	);
}

extern char* file;

void
printfs()
{
	char buf[64];
	char *s;
	
	strcpy(buf, file);
	s = strrchr(buf, '.');
	if (strcmp(s, ".fs") == 0)
		*s = 0;
	for (s = buf; *s; s++)
		if (*s == '.')
			*s = '_';
	s = strrchr(buf, '/');
	if (s)
		s++;
	else
		s = buf;
	
	print("\n#line 0 \"fshandler.inc\"\n"
#include "fshandler.cinc"
	);
	
	print("\n#line 0 \"fsgen/code.c\"");
	print("\n"
	"Srv fs = {\n"
	"	.read = fsread,\n"
	"	.walk1 = fswalk,\n"
	"};\n\n"
	"Srv*\n"
	"getfs_%s()\n", s);
	
	print("#line 0 \"fsfunc.inc\"\n"
#include "fsfunc.cinc"
	);
}

typedef struct Vqid Vqid;
struct Vqid {
	char *name;
	VFile *vfile;
	Vqid *children;
	Vqid *next;
};

Vqid *vqids = nil;

static Vqid*
findchild(Vqid *parent, char *child)
{
	Vqid *v;
	
	for (v = parent->children; v; v = v->next) {
		if (strcmp(v->name, child) == 0)
			return v;
	}
	return nil;
}

void
genqids(VFile *f, void*)
{
	Vqid *v, *nv;
	char **s;
	
	if (!vqids) {
		/* root element */
		vqids = mallocz(sizeof(Vqid), 1);
		vqids->name = "root";
	}
	
	v = vqids;
	for (s = f->parts; *s; s++) {
		if (**s == 0) {
			/* if root element */
			continue;
		}
		nv = findchild(v, *s);
		if (nv) {
			v = nv;
			continue;
		}
		nv = mallocz(sizeof(Vqid), 1);
		nv->name = strdup(*s);
		nv->next = v->children;
		v->children = nv;
		v = nv;
	}
}

static void
rprintqids(Vqid *vq, int nest)
{
	Vqid *v;
	char buf[32];
	if (!vq) return;
	
	for (v = vq; v; v = v->next) {
		pathtostring(buf, sizeof(buf), v->name);
		print("%*sQ%s,\n", nest*4, "", buf);
		rprintqids(v->children, nest+1);
	}
}

void
printqids()
{
	print("enum {\n");
	rprintqids(vqids, 1);
	print("};\n\n");
}