summaryrefslogtreecommitdiffstats
path: root/src/Compiler/TokenScanner.java
blob: ecb5ad335c9e3510146be2e99347c93536f8d62e (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
package Compiler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The lexical scanner, which takes the source code and extracts a list of token objects
 */
public class TokenScanner {
    private String sourceCode;
    List<Token> tokens = new ArrayList<>();
    private int tokenStart=0;
    private int currentLoc=0;
    private int line=0;

    /**
     * Method for extracting tokens, checking each character at a time
     * @param sourceCode the original source code as a string
     * @return a list of tokens represeting the source code
     */
    List<Token> extractTokens(String sourceCode){
        this.sourceCode=sourceCode;
        //Read until the end of the source code as been reached
        while (!checkEOF()){
            tokenStart=currentLoc;
            readToken();
        }
        //Add a EOF token on the end
        tokens.add(new Token(TokenType.EOF, "", null,line));
        return tokens;
    }

    /**
     * Extract a single token
     */
    private void readToken(){
        //Get the current character and find the matching token
        char checkChar = sourceCode.charAt(currentLoc);
        switch(checkChar){

            case ' ':break;
            //Advance line when line break found
            case '\n':
                line++;
                break;
            case '\r':break;
            case '\t':
                break;

            case '(': createTokenNull(TokenType.LEFT_PAREN); break;
            case ')': createTokenNull(TokenType.RIGHT_PAREN); break;
            case '+': createTokenNull(TokenType.PLUS); break;
            case '-': createTokenNull(TokenType.MINUS); break;
            case '*': createTokenNull(TokenType.STAR); break;
            case '/': createTokenNull(TokenType.SLASH); break;
            case ';': createTokenNull(TokenType.SEMI_COLON); break;
            case ',': createTokenNull(TokenType.COMMA); break;

            //Some tokens are multiple characters long
            //so need to check next char as well
            case '=': 
                if (checkNextChar('=')){
                    createTokenNull(TokenType.EQUALITY);
                    break;
                } else {
                    createTokenNull(TokenType.EQUALS);
                    break;
                }

            case ':': 
                if (checkNextChar(':')){
                    createTokenNull(TokenType.DEFINE);
                    break;
                } else {
                    createTokenNull(TokenType.COLON);
                    break;
                }

            case '<': 
                if (checkNextChar('=')){
                    createTokenNull(TokenType.LESS_EQUAL);
                    break;
                } else {
                    createTokenNull(TokenType.LESS);
                    break;
                }

            case '>': 
                if (checkNextChar('=')){
                    createTokenNull(TokenType.GREATER_EQUAL);
                    break;
                } else {
                    createTokenNull(TokenType.GREATER);
                    break;
                }

            case '"':
                while(lookAhead()!='"' && !checkEOF()){
                    currentLoc++;
                }
                if(checkEOF()){
                    Language.displayError(line, "Strings must end with a closing \"");
                    break;
                }
                currentLoc++;
                createToken(TokenType.STRING, sourceCode.substring(tokenStart, currentLoc+1));
                break;

            case '.':
                if(checkIsAlpha(lookAhead()))
                    while (checkIsAlpha(lookAhead())){
                        currentLoc++;
                    } 
                    String logical = sourceCode.substring(tokenStart+1, currentLoc+1);
                    if (checkNextChar('.')){
                        if (logical.equals("and")){
                            createTokenNull(TokenType.AND);
                            break;
                        } else if(logical.equals("or")){
                            createTokenNull(TokenType.OR);
                            break;
                        } else if(logical.equals("not")){
                            createTokenNull(TokenType.NOT);
                            break;
                        } else{
                            Language.displayError(line, "Expected logical expression");
                        }
                    } else {
                        Language.displayError(line, "Expected '.' after logical expression");
                    }
            
            //Find tokens starting with alphanumeric characters
            default:

                //Check for numeric characters
                if (checkIsDigit(checkChar)){
                    String type = "int";
                    while (checkIsDigit(lookAhead())){
                        currentLoc++;
                    }   
                    //Check if number contains a decimal point
                    if (lookAhead()=='.' && checkIsDigit(lookTwoAhead())){
                        type="double";
                        currentLoc++;
                        while (checkIsDigit(lookAhead())){
                            currentLoc++;
                        }
                    }
                    if (type.equals("double")){
                        createToken(TokenType.NUMBER, Double.parseDouble(sourceCode.substring(tokenStart, currentLoc+1)));
                    } else{
                        createToken(TokenType.NUMBER, Integer.parseInt(sourceCode.substring(tokenStart, currentLoc+1)));
                    }
                }

                //Check alphabetical character
                else if (checkIsAlpha(checkChar)){
                    while (checkIsAlpha(lookAhead())){
                        currentLoc++;
                    } 
                    String text = sourceCode.substring(tokenStart, currentLoc+1);

                    //Compare against a list of keywords in the language
                    TokenType type = keywords.get(text);
                    if(type == null){
                        createToken(TokenType.IDENTIFIER, text);
                    } else{
                        createToken(type, text);
                    }
                
                } else {
                    //Report an unknown character
                    Language.displayError(line,"Unexpected Character");
                }
        }
        currentLoc++;

    }

    /**
     * Method to check the end of the source code
     * @return if the end of the source code has been reached
     */
    private boolean checkEOF(){
        return currentLoc>=sourceCode.length();
    }

    /**
     * Create a token with a value of null
     * @param type the token type
     */
    private void createTokenNull(TokenType type){
        createToken(type, null);
    }

    /**
     * Create a token and add to the list
     * @param type the token type
     * @param value the value of the token
     */
    private void createToken(TokenType type, Object value){
        String tokenText = sourceCode.substring(tokenStart, currentLoc+1);
        tokens.add(new Token(type, tokenText, value, line));
    }

    /**
     * Compare the next character in the source code to a given character
     * @param matchChar the character to compare against
     * @return if the character matches
     */
    private boolean checkNextChar(char matchChar){
        if (checkEOF()){
            return false;
        }
        if (sourceCode.charAt(currentLoc+1)==matchChar){
            currentLoc++;
            return true;
        } 
        return false;
    }

    /**
     * gets the next character in the source code
     * @return the next character
     */
    private char lookAhead(){
        if (currentLoc+1>=sourceCode.length()){
            return ' ';

        } else {
            return sourceCode.charAt(currentLoc+1);
        }
    }

    /**
     * look at the character two ahead in the source code
     * @return the character two ahead
     */
    private char lookTwoAhead(){
        if (currentLoc+2>=sourceCode.length()){
            return ' ';

        } else {
            return sourceCode.charAt(currentLoc+2);
        }
    }

    /**
     * checks if a given character is numerical
     * @param checkChar the character to check
     * @return if the character is numerical
     */
    private boolean checkIsDigit(char checkChar){
        return checkChar>='0' && checkChar<='9';
    }

    /**
     * check if a character is alphabetical
     * @param checkChar the character to check
     * @return  if the character is alphabetical
     */
    private boolean checkIsAlpha(char checkChar){
        return ('a'<=checkChar && checkChar<='z')||
               ('A'<=checkChar && checkChar<='Z');
    }

    //A hashmap of the keywords used in the language
    private static final Map<String, TokenType> keywords;

    static {
        keywords = new HashMap<>();
        keywords.put("int",    TokenType.INT);
        keywords.put("len",    TokenType.LEN);
        keywords.put("real",    TokenType.REAL);
        keywords.put("character",    TokenType.STRING);
        keywords.put("print",    TokenType.PRINT);
        keywords.put("endprint",    TokenType.ENDPRINT);
        keywords.put("if",    TokenType.IF);
        keywords.put("then",    TokenType.THEN);
        keywords.put("end",    TokenType.END);
        keywords.put("else",    TokenType.ELSE);
        keywords.put("do",    TokenType.DO);
        keywords.put("while",    TokenType.WHILE);
        keywords.put("dimension",    TokenType.DIMENSION);
        keywords.put("program",    TokenType.PROGRAM);
        keywords.put("return",    TokenType.RETURN);
        keywords.put("function",    TokenType.FUNCTION);
        keywords.put("subroutine",    TokenType.SUBROUTINE);
      }
}