summaryrefslogtreecommitdiff
path: root/tree.c
diff options
context:
space:
mode:
authorVicente <vicente@masba.net>2024-04-02 21:15:25 -0300
committerVicente <vicente@masba.net>2024-04-02 21:15:25 -0300
commit903ff13b3be1c29e35621afcef116329e2da16c8 (patch)
treee36bfa8d6632f53da73832dcfb31bfcb797c3e51 /tree.c
parentf5c501f0c151079a7207ee9b06b779b39e17c55e (diff)
Implemented left recursion descent parser
Diffstat (limited to 'tree.c')
-rw-r--r--tree.c60
1 files changed, 60 insertions, 0 deletions
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 <stdio.h>
+#include <stdlib.h>
+#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<opsize; i++){
+ j=strichar(str,ops[i]);
+ if(j>=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);
+ }
+ }
+}