summaryrefslogtreecommitdiff
path: root/parser.cpp
blob: 8cba19efdfd21253630f8a3f4b1c82250f163977 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <string>
#include "include/parser.hpp"
#include "include/lexer.hpp"
#include "include/exceptions.hpp"

using std::string;

void Parser::setText(string text){
  tokenizer.setText(text); // Se prepara el lexer.
}

bool Parser::checkToken(){
  if(tokenizer.getCurrentToken().type == nil)
    return false;

  return true;
}

void Parser::parse(string expr){
  setText(expr);
  parseExpr();
}

void Parser::parseExpr(){
  parseTerm();
  parsePrimeExpr();
}

void Parser::parsePrimeExpr(){
  if(tokenizer.getCurrentToken().type == sum
     || tokenizer.getCurrentToken().type == substraction)
  {
    tokenizer.nextToken();

    if(!checkToken())
      throw ParserException("Carácter inválido.");

    parseTerm();
    parsePrimeExpr();
  }
}

void Parser::parseTerm(){
  parsePower();
  parsePrimeTerm();
}

void Parser::parsePrimeTerm(){
  if(tokenizer.getCurrentToken().type == multiplication
     || tokenizer.getCurrentToken().type == division)
  {
    tokenizer.nextToken();

    if(!checkToken())
      throw ParserException("Carácter inválido.");

    parsePower();
    parsePrimeTerm();
  }
}

void Parser::parsePower(){
  parseFactor();
  parsePrimePower();
}

void Parser::parsePrimePower(){
  if(tokenizer.getCurrentToken().type == power)
  {
    tokenizer.nextToken();

    if(tokenizer.getCurrentToken().type != number)
      throw ParserException("Sintaxis incorrecta.");

    parsePrimePower();
  }
}

void Parser::parseFactor(){
  switch(tokenizer.getCurrentToken().type)
  {
  case substraction:
    tokenizer.nextToken();
    parseExpr();
    break;
  case left_parens:
    tokenizer.nextToken();
    parseExpr();

    // Consumimos paréntesis derecho.
    if(tokenizer.getCurrentToken().type != right_parens)
      throw ParserException("Sintaxis incorrecta.");
    break;
  case function:
    tokenizer.nextToken();

    if(tokenizer.getCurrentToken().type != left_parens)
      throw ParserException("Sintaxis incorrecta.");

    parseExpr();

    if(tokenizer.getCurrentToken().type != right_parens)
      throw ParserException("Sintaxis incorrecta.");
    
    break;
  case variable:
    tokenizer.nextToken();
    
    break;
  case number:
    tokenizer.nextToken();

    break;
  default:
    throw ParserException("Sintaxis incorrecta.");
    
    break;
  }
}