aboutsummaryrefslogtreecommitdiff
path: root/src/utils.cc
diff options
context:
space:
mode:
authorAdrian Kummerländer2013-09-26 20:41:37 +0200
committerAdrian Kummerländer2013-09-26 20:41:37 +0200
commita0f0c005a39ddaf693c7de84d6ab1c380a93dca2 (patch)
tree53b6c57a9226b2cc67bd577cca169ace199483a0 /src/utils.cc
parentb765b57739463d0aa3b833a70e0ea87bca68e82e (diff)
downloadSimpleParser-a0f0c005a39ddaf693c7de84d6ab1c380a93dca2.tar
SimpleParser-a0f0c005a39ddaf693c7de84d6ab1c380a93dca2.tar.gz
SimpleParser-a0f0c005a39ddaf693c7de84d6ab1c380a93dca2.tar.bz2
SimpleParser-a0f0c005a39ddaf693c7de84d6ab1c380a93dca2.tar.lz
SimpleParser-a0f0c005a39ddaf693c7de84d6ab1c380a93dca2.tar.xz
SimpleParser-a0f0c005a39ddaf693c7de84d6ab1c380a93dca2.tar.zst
SimpleParser-a0f0c005a39ddaf693c7de84d6ab1c380a93dca2.zip
Code restructuring of tree and parsing logic
* Enabled tree to generate itself ** Main work is now done during tree construction * Moved lexer and getPriority utility functions into separate compilation unit
Diffstat (limited to 'src/utils.cc')
-rw-r--r--src/utils.cc115
1 files changed, 115 insertions, 0 deletions
diff --git a/src/utils.cc b/src/utils.cc
new file mode 100644
index 0000000..7457ae2
--- /dev/null
+++ b/src/utils.cc
@@ -0,0 +1,115 @@
+#include "utils.h"
+#include "exceptions.h"
+
+#include "tree.h"
+
+namespace SimpleParser {
+
+int8_t getPriority(char tmp) {
+ switch ( tmp ) {
+ case '-':
+ return 10;
+ case '+':
+ return 10;
+ case '/':
+ return 20;
+ case '*':
+ return 20;
+ case '^':
+ return 30;
+ case '(':
+ return 90;
+ case ')':
+ return 90;
+ case ',':
+ return -1;
+ default:
+ return -1;
+ }
+}
+
+std::vector<std::string> lexer(std::string term) {
+ std::string tmp;
+ std::string tmpNum;
+ std::vector<std::string> output;
+
+ int8_t priority = 0;
+ int8_t lastPriority = 0;
+ uint32_t level = 0;
+
+ for ( auto termIter = term.begin();
+ termIter != term.end();
+ termIter++ ) {
+ priority = getPriority(*termIter);
+
+ if ( priority == -1 || ( termIter == term.begin() &&
+ priority == 10 ) ) {
+ if ( level > 0 ) {
+ tmp += *termIter;
+ } else {
+ tmpNum += *termIter;
+ }
+ } else {
+ if ( lastPriority == -1 && level == 0 ) {
+ output.push_back(tmpNum);
+ tmpNum.clear();
+ }
+
+ switch ( *termIter ) {
+ case '(': {
+ if ( level > 0 ) {
+ tmp += *termIter;
+ }
+
+ level++;
+
+ break;
+ }
+ case ')': {
+ level--;
+
+ if ( level == 0 ) {
+ output.push_back(tmp);
+ tmp.clear();
+ } else {
+ tmp += *termIter;
+ }
+
+ break;
+ }
+ default: {
+ if ( level == 0 ) {
+ std::string helper;
+ helper = *termIter;
+
+ output.push_back(helper);
+ } else {
+ tmp += *termIter;
+ }
+
+ break;
+ }
+ }
+ }
+
+ lastPriority = priority;
+ }
+
+ if ( lastPriority == -1 ) {
+ output.push_back(tmpNum);
+ } else if ( lastPriority != 90 ) {
+ throw operator_exception();
+ }
+
+ if (level != 0) {
+ throw parenthese_exception();
+ }
+
+ if ( lastPriority == 90 && output.size() == 1 ) {
+ output = lexer(output[0]);
+ }
+
+ return output;
+}
+
+}