summaryrefslogtreecommitdiffstats
path: root/src/Compiler/Parser.java
blob: d0556e49f97f2ad8e30fe5bf5e1e0d673aa21d5d (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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package Compiler;

import java.util.ArrayList;
import java.util.List;

import Compiler.Statement.BlockStatement;

public class Parser {
    private final List<Token> tokens;
    private int currentToken = 0;

    Parser(List<Token> tokens){
        this.tokens=tokens;
    }

    List<Statement> parse(){
        List<Statement> statements =  new ArrayList<>();
        try{
            while (!checkEOF()){
                statements.add(statement());
            }
        }catch (Error e){
            return null;
        }
        return statements;
        
    }

    private Statement statement(){
        if(checkToken(TokenType.INT)||checkToken(TokenType.REAL)||checkToken(TokenType.STRING)){
            return declaration();
        }
        else if (matchAndAdvance(TokenType.PRINT)){
            return printStatement();
        }else if (matchAndAdvance(TokenType.IF)){
            return ifStatement();
        }else if (matchAndAdvance(TokenType.DO)){
            return doStatement();
        }
        return expressionStatement();
    }


    //Clean up and reduce code mess
    private Statement declaration(){
        if (matchAndAdvance(TokenType.INT)){
            matchOrError(TokenType.DEFINE, ":: Required for variable definition");
            matchOrError(TokenType.IDENTIFIER,"Expected variable name.");
            Token varName = getPreviousToken();
            return new Statement.VariableDeclaration(varName,"int");
        } else if (matchAndAdvance(TokenType.REAL)){
            matchOrError(TokenType.DEFINE, ":: Required for variable definition");
            matchOrError(TokenType.IDENTIFIER,"Expected variable name.");
            Token varName = getPreviousToken();
            return new Statement.VariableDeclaration(varName,"real");
        
        //Could be improved significatly when verifiying length is a positive integer
        } else if (matchAndAdvance(TokenType.STRING)){
            matchOrError(TokenType.LEFT_PAREN, "Length of string must be defined");
            matchOrError(TokenType.LEN, "Length of string must be defined");
            matchOrError(TokenType.EQUALS, "Length of string must be defined");
            Expression length = expression();
            if(!(length instanceof Expression.Literal)){
                throw error(getCurrentToken(),"String length must be a number");
            }
            if(!((Expression.Literal)length).type.equals("int")){
                throw error(getCurrentToken(),"String length must be a integer"); 
            }
            if((int)((Expression.Literal)length).value.value<1){
                throw error(getCurrentToken(),"String length must be greater then 0"); 
            }
            matchOrError(TokenType.RIGHT_PAREN, "Length of string must be defined");

            matchOrError(TokenType.DEFINE, ":: Required for variable definition");
            matchOrError(TokenType.IDENTIFIER,"Expected variable name.");
            Token varName = getPreviousToken();
            return new Statement.StringDeclaration(varName,length);
        }
        return null;
    }

    private BlockStatement blockStatement(){
        List<Statement> statements = new ArrayList<>();
        while(!matchAndAdvance(TokenType.END)&&!checkToken(TokenType.ELSE)){
            if(checkEOF()){
                throw error(getCurrentToken(),"end missing from block");
            }
            statements.add(statement());
        }
        return new Statement.BlockStatement(statements);
    }

    private Statement printStatement(){
        matchOrError(TokenType.STAR, "Syntax, print *, item1, item2...");
        List<Expression> exprList = new ArrayList<>();
        while(matchAndAdvance(TokenType.COMMA)){
            if(checkEOF()){
                throw error(getCurrentToken(),"reached end of file");
            }
            Expression expr = expression();
            exprList.add(expr);
        }
        return new Statement.PrintStatement(exprList);
    }

    //Could be cleaned up to handle else statements better
    private Statement ifStatement(){
        Expression condition = expression();
        if(matchOrError(TokenType.THEN, "then expected after if statement")){
            Statement.BlockStatement ifBlock = blockStatement();
            Statement.BlockStatement elseBlock=null;
            
            if(matchAndAdvance(TokenType.ELSE)){
                elseBlock=blockStatement();
            }
            matchOrError(TokenType.IF, "If statements end with if");
            Statement ifstatement = new Statement.IfStatement(condition, ifBlock,elseBlock);
            return ifstatement;
        }
        return null;
    }

    private Statement doStatement(){
        if(matchAndAdvance(TokenType.WHILE)){
            return whileStatement();
        }
        Expression variable =expression();
        matchOrError(TokenType.EQUALS, "'=' missing");
        Expression start = expression();
        matchOrError(TokenType.COMMA, " use ',' between values");
        Expression stop = expression();
        Expression step = null;
        if(matchAndAdvance(TokenType.COMMA)){
           step = expression();
        }
        Statement.BlockStatement codeBlock = blockStatement();
        matchOrError(TokenType.DO, "Do statements end with do");
        return new Statement.DoStatement(variable, start, stop, step,codeBlock);

    }

    private Statement whileStatement(){
        matchOrError(TokenType.LEFT_PAREN, " missing '(' for do statement condition");
        Expression condition = expression();
        matchOrError(TokenType.RIGHT_PAREN, " missing ')' for do  condition");
        Statement.BlockStatement codeBlock = blockStatement();
        matchOrError(TokenType.DO, "Do while statements end with do");
        return new Statement.DoWhileStatement(condition,codeBlock);
    }

    private Statement expressionStatement(){
        Expression expression = assignment();
        return new Statement.ExpressionStatement(expression);
    }

    private Expression assignment(){
        Expression variable = expression();
        if (matchAndAdvance(TokenType.EQUALS)){
            Expression assignedvalue = expression();

            if (variable instanceof Expression.Variable){
                return new Expression.AssignmentExpression(((Expression.Variable)variable).name,assignedvalue);
            }
            throw error(getCurrentToken(),"Left of assignment must be a variable");
        }
        return variable;
    }

    private Expression expression(){
        Expression createdExpression = equality();
        return createdExpression;
    }

    private Expression equality(){
        Expression createdExpression = logical();
        while (matchAndAdvance(TokenType.EQUALITY)){
            Token op = getPreviousToken();
            Expression right = logical();
            createdExpression = new Expression.Binary(createdExpression, op, right);
        }
        return createdExpression;
    }

    private Expression logical(){
        if(matchAndAdvance(TokenType.NOT)){
            Token op = getPreviousToken();
            Expression right = comparison();
            Expression createdExpression = new Expression.Singular(op, right);
            return createdExpression;
        }
        Expression createdExpression = comparison();
        while (matchAndAdvance(TokenType.AND)||matchAndAdvance(TokenType.OR)){
            Token op = getPreviousToken();
            Expression right = comparison();
            createdExpression = new Expression.Binary(createdExpression, op, right);
        }
        return createdExpression;
    }

    private Expression comparison(){
        Expression createdExpression = term();
        while (matchAndAdvance(TokenType.GREATER)||matchAndAdvance(TokenType.LESS)||matchAndAdvance(TokenType.GREATER_EQUAL)||matchAndAdvance(TokenType.LESS_EQUAL)){
            Token op = getPreviousToken();
            Expression right = term();
            createdExpression = new Expression.Binary(createdExpression, op, right);
        }
        return createdExpression;
    }

    private Expression term(){
        Expression createdExpression = factor();
        while (matchAndAdvance(TokenType.PLUS)||matchAndAdvance(TokenType.MINUS)){
            Token op = getPreviousToken();
            Expression right = factor();
            createdExpression = new Expression.Binary(createdExpression, op, right);
        }
        return createdExpression;
    }

    private Expression factor(){
        Expression createdExpression = primary();
        while (matchAndAdvance(TokenType.STAR)||matchAndAdvance(TokenType.SLASH)){
            Token op = getPreviousToken();
            Expression right = primary();
            createdExpression = new Expression.Binary(createdExpression, op, right);
        }
        return createdExpression;
    }

    private Expression primary(){
        if (matchAndAdvance(TokenType.NUMBER)){
            if(getPreviousToken().value instanceof Integer){
                return new Expression.Literal(getPreviousToken(),"int");
            } else if(getPreviousToken().value instanceof Double){
                return new Expression.Literal(getPreviousToken(),"double");
            }
        }
        if (matchAndAdvance(TokenType.STRING)){
            return new Expression.Literal(getPreviousToken(), "string");
        }

        if (matchAndAdvance(TokenType.IDENTIFIER)) {

            return new Expression.Variable(getPreviousToken());
          }

        if (matchAndAdvance(TokenType.LEFT_PAREN)){
            Expression expr = expression();
            matchOrError(TokenType.RIGHT_PAREN,"Expected ')'");
            return new Expression.BracketedExpression(expr);
        }
        throw error(getCurrentToken(),"Unknown syntax error");
    }

    private void advanceToken(){
        if (!checkEOF()) {
            currentToken++;
        };
    }

    private boolean matchAndAdvance(TokenType type){
        if (checkToken(type)) {
            advanceToken();
            return true;
        }
        return false;
    }

    private boolean matchOrError(TokenType type,String errorMessage){
        if (matchAndAdvance(type)){
            return true;
        }
        throw error(getCurrentToken(),errorMessage);
    }

    private boolean checkToken(TokenType type){
        if (checkEOF()) return false;
        return getCurrentToken().type == type; 
    }

    private boolean checkEOF(){
        return tokens.get(currentToken).type==TokenType.EOF;
    }

    private Token getCurrentToken(){
        return tokens.get(currentToken);
    }

    private Token getPreviousToken(){
        return tokens.get(currentToken - 1);
    }

    private Error error(Token token, String message){
        Language.displayError(token ,message);
        return new Error();
    }


}