diff --git a/bfpcompiler/include/analyzer.h b/bfpcompiler/include/analyzer.h index 058a71f..38a80cd 100644 --- a/bfpcompiler/include/analyzer.h +++ b/bfpcompiler/include/analyzer.h @@ -1,6 +1,16 @@ #ifndef ANALYZER_H #define ANALYZER_H +#include +#include +/** + * @name analyze + * @return int + * @brief Analyze the tokens syntax. Return -1 on error and 1 on warning, 0 else. + * + * @param char* tokens: analyze_tokens + */ +int analyze (char* tokens); #endif//ANALYZER_H diff --git a/bfpcompiler/src/analyzer.c b/bfpcompiler/src/analyzer.c index 5a16681..fbe0720 100644 --- a/bfpcompiler/src/analyzer.c +++ b/bfpcompiler/src/analyzer.c @@ -1 +1,45 @@ #include "../include/analyzer.h" + +/** + * @name analyze + * @return int + * @brief Check for errors and warnings. + * + * @param char* token + */ +int analyze (char* token) { + int rv = 0; + int position = 0; + + for (char* cursor = token; *cursor; cursor++) { + + /* Analyze form */ + if (*cursor == '[') { + rv += 1; + } else if (*cursor == ']') { + rv -= 1; + } + + /* Check value for errors. */ + if (rv < 0) { + (void)printf("Error on token %d\n", position); + perror("ERROR: Closing bracket without opening bracket!"); + rv = EXIT_FAILURE; + break; + } + + /* check for nested loops */ + if (rv > 1) { + (void)printf("Warning on token %d\n", position); + (void)printf("WARNING: Nested loops are not supported on all versions of the target device!\n"); + } + } + + if (rv > 0) { + (void)printf("There are %d loops without end!\n", rv); + perror("ERROR: Loop not closed!"); + rv = EXIT_FAILURE; + } + + return rv; +}