-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken.ts
51 lines (46 loc) · 1.06 KB
/
token.ts
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
export enum TokenType {
NUMBER,
IDENTIFIER,
VARIABLE,
UNARY_OPERATOR,
BINARY_OPERATOR,
LEFT_PAREN,
RIGHT_PAREN,
COMMA,
}
export class Token {
constructor(
public type: TokenType,
public pattern: RegExp,
public symbol?: string
) {}
match(input: string): number {
const result = input.match(this.pattern);
if (result && result.length > 0) {
return result[0].length;
}
return -1;
}
toString() {
if (this.symbol === undefined) {
return this.type;
} else {
return `${this.type} '${this.symbol}'`;
}
}
}
export const LEFT_PAREN = new Token(TokenType.LEFT_PAREN, /^\(/, "(");
export const RIGHT_PAREN = new Token(TokenType.RIGHT_PAREN, /^\)/, ")");
export const COMMA = new Token(TokenType.COMMA, /^,/, ",");
export const NUMBER = new Token(
TokenType.NUMBER,
/^([0-9]+[.])?[0-9]+([eE][-+]?[0-9]+)?/
);
export const IDENTIFIER = new Token(
TokenType.IDENTIFIER,
/^\p{L}([0-9]|\p{L})*/u
);
export const VARIABLE = new Token(
TokenType.VARIABLE,
/^[<]\p{L}(([0-9_-]|\p{L})*([0-9]|\p{L})+)?/u
);