diff --git a/src/compile.c b/src/compile.c index 357d617..50d4251 100644 --- a/src/compile.c +++ b/src/compile.c @@ -1,8 +1,15 @@ #include +#include #include #include "syntax.h" +void string_append(char** string, char* append) { + int len = strlen(*string); + *string = realloc(*string, len + strlen(append) + sizeof(char)); + strcpy(*string + len, append); +} + void compile_enter_tag(char** string) { int len = strlen(*string); *string = realloc(*string, len + 3 * sizeof(char)); @@ -19,10 +26,52 @@ void compile_exit_tag(char** string) { string[0][len + 2] = '\0'; } -void string_append(char** string, char* append) { - int len = strlen(*string); - *string = realloc(*string, len + strlen(append) + sizeof(char)); - strcpy(*string + len, append); +bool compile_isop(char* string) { + if (strcmp(string, "+") == 0) return true; + else if (strcmp(string, "-") == 0) return true; + else if (strcmp(string, "*") == 0) return true; + else if (strcmp(string, "/") == 0) return true; + else return false; +} + +char* compile_expression(tSyntaxElement* syntaxelement) { + char* result = calloc(1,sizeof(char)); + string_append(&result, "("); + switch (syntaxelement->type) { + case TOKEN: + string_append(&result, syntaxelement->content.string); + break; + case STRING: + string_append(&result, "\""); + string_append(&result, syntaxelement->content.string); + string_append(&result, "\""); + break; + case TREE: + if (se_istraversable(syntaxelement)) { + if (syntaxelement->content.syntax->type == TOKEN) { + tSyntaxElement* token = syntaxelement->content.syntax; + if (compile_isop(token->content.string)) { + char* operator = token->content.string; + while (1) { + if (token->next != NULL) { + string_append(&result,token->next->content.string); + if (token->next->next != NULL) { + string_append(&result,operator); + } + token = token->next; + } else break; + } + } + } + } + break; + case NEWTREE: + case NONE: + free(result); + return NULL; + } + string_append(&result, ")"); + return result; } char* compile(tSyntaxElement* syntaxtree) { @@ -37,7 +86,7 @@ char* compile(tSyntaxElement* syntaxtree) { string_append(&result, "set "); string_append(&result,token->next->content.string); string_append(&result,"="); - string_append(&result,token->next->next->content.string); + string_append(&result,compile_expression(token->next->next)); compile_exit_tag(&result); } }