From 903ff13b3be1c29e35621afcef116329e2da16c8 Mon Sep 17 00:00:00 2001 From: Vicente Date: Tue, 2 Apr 2024 21:15:25 -0300 Subject: Implemented left recursion descent parser --- .gitignore | 1 + Makefile | 2 +- main.c | 9 ++++++--- tree.c | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ tree.h | 18 +++++++++--------- 5 files changed, 77 insertions(+), 13 deletions(-) create mode 100644 tree.c diff --git a/.gitignore b/.gitignore index e660fd9..e86b018 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ bin/ +a.out diff --git a/Makefile b/Makefile index 2e857bc..98af738 100644 --- a/Makefile +++ b/Makefile @@ -12,7 +12,7 @@ EXES := $(ARCFIND) CFLAGS := $(addprefix -I,$(SRCDIRS)) $(XTRAFLAGS) LDLIBS := -ARCFIND_O := $(addprefix ./bin/, main.o) +ARCFIND_O := $(addprefix ./bin/, main.o, tree.o) all: $(EXES) .PHONY: all diff --git a/main.c b/main.c index bfea3b3..566330c 100644 --- a/main.c +++ b/main.c @@ -1,6 +1,9 @@ #include +#include "tree.h" -int main(void) { - printf("arcfind!\n"); - return 0; +int main(){ + char str[100]; + printf("type in your tree(no spaces please): "); + scanf("%[^\n]", str); + printTree(parse(str),0); } diff --git a/tree.c b/tree.c new file mode 100644 index 0000000..e5fc435 --- /dev/null +++ b/tree.c @@ -0,0 +1,60 @@ +#include +#include +#include "tree.h" + +int strichar(const char *str, char c){ + for(int i=0; str[i]!='\0';i++){ + if(str[i] == c) return i; + } + return -1; //char not found +} +const char ops[] = {'+','*','!'}; //ordem inversa +const int opsize = sizeof(ops)/sizeof(char); +node * parse(char *str) { //expects a string with no whitespace + + int j,i; + for(i=0; i=0) break; + } + + node *this = (node *)malloc(sizeof(node)); + + if(j<0) { + this->type = LTTR; + this->el = str[0]; + } + + else{ + this->el = ops[i]; + if(i==2) { + this->type = UNOP; + this->child[0] = parse(str+j+1); + } + else { + str[j] = '\0'; + this->type = BIOP; + this->child[0] = parse(str); + this->child[1] = parse(str+j+1); + } + } + return this; +} + +void printTree(node *root, int level) { + if (root == NULL) + return; + + if (level) { + for (int i = 1; i < level; i++) { + printf("│ "); + } + printf("├─ "); + } + printf("%c\n", root->el); + for (int i = 0; i < 2; i++) { + if (root->child[i] != NULL) { + printTree(root->child[i], level + 1); + } + } +} diff --git a/tree.h b/tree.h index cf4d825..a58d270 100644 --- a/tree.h +++ b/tree.h @@ -1,13 +1,13 @@ enum nodeType { - BIOP, - UNOP, - LTTR + BIOP, + UNOP, + LTTR }; -typedef struct { - enum nodeType type; - char el; - struct node *child[2]; +typedef struct node { + enum nodeType type; + char el; + struct node *child[2]; } node; - -node* parse(const char *str); +node * parse(char *str); +void printTree(node *root, int level); -- cgit v1.2.3