Skip to content
Snippets Groups Projects
Commit cae50ade authored by Lu Wang's avatar Lu Wang
Browse files

Added translate function to get a list-style parse tree for pattern matching

parent f7924ced
No related branches found
No related tags found
No related merge requests found
......@@ -32,6 +32,9 @@ SQLPProgram
n->children[0] = $1;
printf("Printing Tree\n");
print_tree(n, 0);
struct linked_node *linked_tree = malloc(sizeof(struct linked_node));
translate(linked_tree, n);
print_linked_tree(linked_tree, 0);
}
;
......@@ -39,7 +42,7 @@ Identifier
: IDENTIFIER
{ printf("|%s| ", yytext);
$$ = new_node(1, Identifier);
$$->children[0] = $1;
$$->children[0] = new_node(0, IDENTIFIER);
}
;
......
......@@ -29,4 +29,52 @@ void destroy_tree(struct node *root) {
destroy_tree(root->children[i]);
}
free(root);
}
\ No newline at end of file
}
// translate the parse tree to a linked structure
// next points to its sibling
// children points to its first child
void translate(struct linked_node *linked_tree, struct node *tree) {
if (tree == NULL) return;
linked_tree->type = tree->type;
int count = tree->count;
if (count > 0) {
struct linked_node *first_child = malloc(sizeof(struct linked_node));
linked_tree->children = first_child;
} else {
linked_tree->children = NULL;
}
struct linked_node *current_node = linked_tree->children;
for (int i = 1; i < count; i++) {
current_node->next = malloc(sizeof(struct linked_node));
current_node = current_node->next;
}
if (current_node) current_node->next = NULL;
current_node = linked_tree->children;
for (int i = 0; i < count; i++) {
translate(current_node, tree->children[i]);
current_node = current_node->next;
}
}
void print_linked_tree(struct linked_node *root, int level) {
if (root == NULL) {
return;
}
if (root->children != NULL){
printf("level: %d, type: %s\n", indent, node_types[root->type]);
}
print_linked_tree(root->next, level);
print_linked_tree(root->children, level+1);
}
// translated from PatMatch.cl
// bool match(struct node *pat, struct node *tree) {
// if (pat->next != NULL) {
// return (tree->next != NULL && match(pat->children, tree->children) &&
// match(pat->next, children->next);
// }
// }
......@@ -11,6 +11,12 @@ struct node {
};
struct linked_node {
int type;
struct linked_node *next; // siblings
struct linked_node *children;
};
enum type {
SQLPProgram,
......@@ -28,10 +34,12 @@ enum type {
};
struct node *new_node(int count, int type);
void translate(struct linked_node *linked_tree, struct node *tree);
void print_tree(struct node *root, int indent);
void print_linked_tree(struct linked_node *root, int indent);
void destroy_tree(struct node *root);
bool match(struct linked_node *pat, struct linked_node *tree);
#endif
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment