Skip to content

Instantly share code, notes, and snippets.

@codedot
Created November 24, 2012 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codedot/4139831 to your computer and use it in GitHub Desktop.
Save codedot/4139831 to your computer and use it in GitHub Desktop.
Tree Exercise
#include <stdio.h>
#include <stdlib.h>
#define BEGIN \
"#include <stdio.h>\n" \
"#include <stdlib.h>\n" \
"\n" \
"static struct tree {\n" \
"\tstruct tree *left, *right;\n" \
"} *buf[BUFSIZ];\n" \
"\n" \
"static void output(tree)\n" \
"\tstruct tree *tree;\n" \
"{\n" \
"\tif (!tree) {\n" \
"\t\tputchar('0');\n" \
"\t\treturn;\n" \
"\t}\n" \
"\n" \
"\tputchar('1');\n" \
"\toutput(tree->left);\n" \
"\toutput(tree->right);\n" \
"}\n" \
"\n" \
"int main()\n" \
"{"
#define END \
"\toutput(buf[0]);\n" \
"\tputchar('\\n');\n" \
"\treturn 0;\n" \
"}"
/* Grammar: <tree> ::= '0' | '1' <tree> <tree>. */
static char *input;
static struct tree {
struct tree *left, *right;
} *mktree()
{
struct tree *tree = NULL;
if ('1' == *input) {
tree = malloc(sizeof *tree);
++input;
tree->left = mktree();
++input;
tree->right = mktree();
}
return tree;
}
static void gen(tree)
struct tree *tree;
{
/* TODO: print some code in stdout. */
}
int main(argc, argv)
char *argv[];
{
input = argv[argc - 1];
puts(BEGIN);
gen(mktree());
puts(END);
return 0;
}
TEST = 0
all: gentree
./gentree $(TEST) >output.c
$(MAKE) output
[ $(TEST) = $$(./output) ]
clean:
-rm -f gentree output output.c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment