-
Notifications
You must be signed in to change notification settings - Fork 2
/
token.pas
131 lines (105 loc) · 3.11 KB
/
token.pas
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
{
Crafting Interpreters
https://craftinginterpreters.com/
}
unit token;
{$ifdef FPC}
{$mode delphi}
{$endif}
interface
uses
Classes, SysUtils, Generics.Collections
, ptypes;
type
TTokenKind = (
// Single-character tokens.
tkLEFT_PAREN, tkRIGHT_PAREN, // ( , )
tkLEFT_BRACE, tkRIGHT_BRACE, // { , }
tkCOMMA, tkDOT, // , , .
tkMINUS, tkPLUS, // - , +
tkSEMICOLON, tkSTAR, // ; , *
tkSLASH, // /
// One or two character tokens.
tkBANG, tkBANG_EQUAL,
tkEQUAL, tkEQUAL_EQUAL,
tkLESS, tkLESS_EQUAL,
tkGREATER, tkGREATER_EQUAL,
// Literals.
tkIDENTIFIER, tkSTRING, tkNUMBER,
// Keywords.
tkAND, tkOR, tkTRUE, tkFALSE,
tkCLASS, tkSUPER, tkTHIS,
tkIF, tkELSE, tkFOR, tkWHILE, tkBREAK,
tkFUN, tkRETURN,
tkVAR, tkNIL,
tkPRINT, tkPRINTDOT,
// End of file.
tkEOF);
{ TToken }
TToken = class
private
FTokenKind: TTokenKind;
FLexeme: string;
FLiteral: TLoxObject;
FLine: integer;
public
constructor Create(tokenKind: TTokenKind; lexeme: string;
literal: TLoxObject; line: integer);
destructor Destroy; override;
function ToString: string; override;
property tokenKind: TTokenKind read FTokenKind;
property lexeme: string read FLexeme;
property literal: TLoxObject read FLiteral;
property line: integer read FLine;
end;
var
loxKeywords: TDictionary<string, TTokenKind>;
implementation
uses TypInfo;
constructor TToken.Create(tokenKind: TTokenKind; lexeme: string;
literal: TLoxObject; line: integer);
begin
FTokenKind := tokenKind;
FLexeme := lexeme;
FLiteral := literal;
FLine := line;
end;
destructor TToken.Destroy;
begin
FreeAndNil(self.FLiteral);
inherited Destroy;
end;
function TToken.ToString: string;
begin
{ Original format }
Result := Format('%s %s %s', [GetEnumName(TypeInfo(TTokenKind), Ord(self.FTokenKind)).Substring(2),
self.FLexeme, ObjToStr(self.FLiteral)]);
(* JSON
Result := Format('{ tokenKind: %s, lexeme: "%s", literal: %s }',
[GetEnumName(TypeInfo(TTokenKind), Ord(self.FTokenKind)),
self.FLexeme, ObjToStr(self.FLiteral)]);
*)
end;
initialization
loxKeywords := TDictionary<string, TTokenKind>.Create();
loxKeywords.Add('and', TTokenKind.tkAND);
loxKeywords.Add('or', TTokenKind.tkOR);
loxKeywords.Add('true', TTokenKind.tkTRUE);
loxKeywords.Add('false', TTokenKind.tkFALSE);