-
Notifications
You must be signed in to change notification settings - Fork 0
/
lexer.js
87 lines (69 loc) · 2.25 KB
/
lexer.js
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
'use strict';
let InputRegex = require('./input-regex');
let TokenType = require('./token-type');
let Token = require('./token');
const charRegex = /[a-z0-9]/i
class Lexer {
constructor(regex) {
this.inputRegex = new InputRegex(regex);
this.currentSymbol = this.inputRegex.getNextSymbol();
}
getTokens() {
let tokens = [];
let currentToken = this.getNextToken();
while(currentToken.type !== TokenType.EOF) {
tokens.push(currentToken);
currentToken = this.getNextToken();
}
return tokens;
}
getNextToken() {
while(this.currentSymbol.char === ' ') this.nextSymbol();
if(this.currentSymbol.char === '$') {
return this.buildToken(TokenType.EOF);
}
if(this.isSymbolCharacter()) {
let token = this.buildToken(TokenType.CHARACTER);
this.nextSymbol();
return token;
}
if(this.currentSymbol.char === '*') {
let token = this.buildToken(TokenType.OP_CLOSURE);
this.nextSymbol();
return token;
}
if(this.currentSymbol.char === '.') {
let token = this.buildToken(TokenType.OP_CONCAT);
this.nextSymbol();
return token;
}
if(this.currentSymbol.char === '+') {
let token = this.buildToken(TokenType.OP_UNION);
this.nextSymbol();
return token;
}
if(this.currentSymbol.char === '(') {
let token = this.buildToken(TokenType.PARENTHESIS_OPEN);
this.nextSymbol();
return token;
}
if(this.currentSymbol.char === ')') {
let token = this.buildToken(TokenType.PARENTHESIS_CLOSE);
this.nextSymbol();
return token;
}
throw `Unrecognized token at column ${this.currentSymbol.col}`;
}
buildToken(tokenType) {
let char = this.currentSymbol.char;
let col = this.currentSymbol.col;
return new Token(char, tokenType, col);
}
nextSymbol() {
this.currentSymbol = this.inputRegex.getNextSymbol();
}
isSymbolCharacter() {
return this.currentSymbol.char.match(charRegex);
}
}
module.exports = Lexer;