forked from bkiers/python3-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonLexerBase.js
More file actions
308 lines (271 loc) · 12.2 KB
/
PythonLexerBase.js
File metadata and controls
308 lines (271 loc) · 12.2 KB
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
300
301
302
303
304
305
306
307
308
/*
The MIT License (MIT)
Copyright (c) 2021 Robert Einhorn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*
*
* Project : A helper class for an ANTLR4 Python lexer grammar that assists in tokenizing indentation
*
* Developed by : Robert Einhorn, [email protected]
*
*/
'use strict';
import { Token, Lexer } from "antlr4";
import PythonLexer from "./PythonLexer.js";
export default class PythonLexerBase extends Lexer {
// A stack that keeps track of the indentation lengths
#indentLengthStack;
// A list where tokens are waiting to be loaded into the token stream
#pendingTokens;
// Last pending token types
#previousPendingTokenType;
#lastPendingTokenTypeFromDefaultChannel;
// Count of open parentheses, square brackets, and curly braces
#opened;
#wasSpaceIndentation;
#wasTabIndentation;
#wasIndentationMixedWithSpacesAndTabs;
#curToken; // current (under processing) token
#ffgToken; // following (look ahead) token
get #INVALID_LENGTH() { return -1; }
get #ERR_TXT() { return " ERROR: "; }
constructor(input) {
super(input);
this.#init();
}
nextToken() { // reading the input stream until a return EOF
this.#checkNextToken();
return this.#pendingTokens.shift() /* .pollFirst() */; // Add the queued token to the token stream
}
reset() {
this.#init();
super.reset();
}
#init() {
this.#indentLengthStack = [];
this.#pendingTokens = [];
this.#previousPendingTokenType = 0;
this.#lastPendingTokenTypeFromDefaultChannel = 0;
this.#opened = 0;
this.#wasSpaceIndentation = false;
this.#wasTabIndentation = false;
this.#wasIndentationMixedWithSpacesAndTabs = false;
this.#curToken = null;
this.#ffgToken = null;
}
#checkNextToken() {
if (this.#previousPendingTokenType === Token.EOF) return;
this.#setCurrentAndFollowingTokens();
if (this.#indentLengthStack.length === 0) { // We're at the first token
this.#handleStartOfInput();
}
switch (this.#curToken.type) {
case PythonLexer.LPAR:
case PythonLexer.LSQB:
case PythonLexer.LBRACE:
this.#opened++;
this.#addPendingToken(this.#curToken);
break;
case PythonLexer.RPAR:
case PythonLexer.RSQB:
case PythonLexer.RBRACE:
this.#opened--;
this.#addPendingToken(this.#curToken);
break;
case PythonLexer.NEWLINE:
this.#handleNEWLINEtoken();
break;
case PythonLexer.ERRORTOKEN:
this.#reportLexerError(`token recognition error at: '${this.#curToken.text}'`);
this.#addPendingToken(this.#curToken);
break;
case Token.EOF:
this.#handleEOFtoken();
break;
default:
this.#addPendingToken(this.#curToken);
}
}
#setCurrentAndFollowingTokens() {
this.#curToken = this.#ffgToken == undefined ?
super.nextToken() :
this.#ffgToken;
this.#ffgToken = this.#curToken.type === Token.EOF ?
this.#curToken :
super.nextToken();
}
// initialize the _indentLengthStack
// hide the leading NEWLINE token(s)
// if exists, find the first statement (not NEWLINE, not EOF token) that comes from the default channel
// insert a leading INDENT token if necessary
#handleStartOfInput() {
// initialize the stack with a default 0 indentation length
this.#indentLengthStack.push(0); // this will never be popped off
while (this.#curToken.type !== Token.EOF) {
if (this.#curToken.channel === Token.DEFAULT_CHANNEL) {
if (this.#curToken.type === PythonLexer.NEWLINE) {
// all the NEWLINE tokens must be ignored before the first statement
this.#hideAndAddPendingToken(this.#curToken);
} else { // We're at the first statement
this.#insertLeadingIndentToken();
return; // continue the processing of the current token with #checkNextToken()
}
} else {
this.#addPendingToken(this.#curToken); // it can be WS, EXPLICIT_LINE_JOINING or COMMENT token
}
this.#setCurrentAndFollowingTokens();
} // continue the processing of the EOF token with #checkNextToken()
}
#insertLeadingIndentToken() {
if (this.#previousPendingTokenType === PythonLexer.WS) {
let prevToken = this.#pendingTokens.at(- 1) /* stack peek */; // WS token
if (this.#getIndentationLength(prevToken.text) !== 0) { // there is an "indentation" before the first statement
const errMsg = "first statement indented";
this.#reportLexerError(errMsg);
// insert an INDENT token before the first statement to trigger an 'unexpected indent' error later in the parser
this.#createAndAddPendingToken(PythonLexer.INDENT, Token.DEFAULT_CHANNEL, this.#ERR_TXT + errMsg, this.#curToken);
}
}
}
#handleNEWLINEtoken() {
if (this.#opened > 0) { // We're in an implicit line joining, ignore the current NEWLINE token
this.#hideAndAddPendingToken(this.#curToken);
return;
}
let nlToken = this.#curToken.clone(); // save the current NEWLINE token
const isLookingAhead = this.#ffgToken.type === PythonLexer.WS;
if (isLookingAhead) {
this.#setCurrentAndFollowingTokens(); // set the next two tokens
}
switch (this.#ffgToken.type) {
case PythonLexer.NEWLINE: // We're before a blank line
case PythonLexer.COMMENT: // We're before a comment
this.#hideAndAddPendingToken(nlToken);
if (isLookingAhead) {
this.#addPendingToken(this.#curToken); // WS token
}
break;
default:
this.#addPendingToken(nlToken);
if (isLookingAhead) { // We're on whitespace(s) followed by a statement
const indentationLength = this.#ffgToken.type === Token.EOF ?
0 :
this.#getIndentationLength(this.#curToken.text);
if (indentationLength !== this.#INVALID_LENGTH) {
this.#addPendingToken(this.#curToken); // WS token
this.#insertIndentOrDedentToken(indentationLength); // may insert INDENT token or DEDENT token(s)
} else {
this.#reportError("inconsistent use of tabs and spaces in indentation");
}
} else { // We're at a newline followed by a statement (there is no whitespace before the statement)
this.#insertIndentOrDedentToken(0); // may insert DEDENT token(s)
}
}
}
#insertIndentOrDedentToken(curIndentLength) {
let prevIndentLength = this.#indentLengthStack.at(-1) /* stack peek */;
if (curIndentLength > prevIndentLength) {
this.#createAndAddPendingToken(PythonLexer.INDENT, Token.DEFAULT_CHANNEL, null, this.#ffgToken);
this.#indentLengthStack.push(curIndentLength);
} else {
while (curIndentLength < prevIndentLength) { // more than 1 DEDENT token may be inserted to the token stream
this.#indentLengthStack.pop();
prevIndentLength = this.#indentLengthStack.at(-1) /* stack peek */;
if (curIndentLength <= prevIndentLength) {
this.#createAndAddPendingToken(PythonLexer.DEDENT, Token.DEFAULT_CHANNEL, null, this.#ffgToken);
} else {
this.#reportError("inconsistent dedent");
}
}
}
}
#insertTrailingTokens() {
switch (this.#lastPendingTokenTypeFromDefaultChannel) {
case PythonLexer.NEWLINE:
case PythonLexer.DEDENT:
break; // no trailing NEWLINE token is needed
default:
// insert an extra trailing NEWLINE token that serves as the end of the last statement
this.#createAndAddPendingToken(PythonLexer.NEWLINE, Token.DEFAULT_CHANNEL, null, this.#ffgToken); // _ffgToken is EOF
}
this.#insertIndentOrDedentToken(0); // Now insert as much trailing DEDENT tokens as needed
}
#handleEOFtoken() {
if (this.#lastPendingTokenTypeFromDefaultChannel > 0) {
// there was a statement in the input (leading NEWLINE tokens are hidden)
this.#insertTrailingTokens();
}
this.#addPendingToken(this.#curToken);
}
#hideAndAddPendingToken(originalToken) {
originalToken.channel = Token.HIDDEN_CHANNEL;
this.#addPendingToken(originalToken);
}
#createAndAddPendingToken(type, channel, text, originalToken) {
const token = originalToken.clone();
token.type = type;
token.channel = channel;
token.stop = originalToken.start - 1;
token.text = text == null ?
`<${this.getSymbolicNames()[type]}>` :
text;
this.#addPendingToken(token);
}
#addPendingToken(token) {
// save the last pending token type because the _pendingTokens linked list can be empty by the nextToken()
this.#previousPendingTokenType = token.type;
if (token.channel === Token.DEFAULT_CHANNEL) {
this.#lastPendingTokenTypeFromDefaultChannel = this.#previousPendingTokenType;
}
this.#pendingTokens.push(token) /* .addLast(token) */;
}
#getIndentationLength(indentText) { // the indentText may contain spaces, tabs or form feeds
const TAB_LENGTH = 8; // the standard number of spaces to replace a tab to spaces
let length = 0;
for (let ch of indentText) {
switch (ch) {
case " ":
this.#wasSpaceIndentation = true;
length += 1;
break;
case "\t":
this.#wasTabIndentation = true;
length += TAB_LENGTH - (length % TAB_LENGTH);
break;
case "\f": // form feed
length = 0;
break;
}
}
if (this.#wasTabIndentation && this.#wasSpaceIndentation) {
if (!this.#wasIndentationMixedWithSpacesAndTabs) {
this.#wasIndentationMixedWithSpacesAndTabs = true;
length = this.#INVALID_LENGTH; // only for the first inconsistent indent
}
}
return length;
}
#reportLexerError(errMsg) {
this.getErrorListener().syntaxError(this, this.#curToken.type, this.#curToken.line, this.#curToken.column, " LEXER" + this.#ERR_TXT + errMsg, null);
}
#reportError(errMsg) {
this.#reportLexerError(errMsg);
this.#createAndAddPendingToken(PythonLexer.ERRORTOKEN, Token.DEFAULT_CHANNEL, this.#ERR_TXT + errMsg, this.#ffgToken);
// the ERRORTOKEN also triggers a parser error
}
}