summaryrefslogtreecommitdiffstats
path: root/contrib/restricted/wavm/Lib/WASTParse/Lexer.cpp
blob: 26a7be2e1dad1d0458b5e88d8a7bd05acd8a2091 (plain) (blame)
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
#include "Lexer.h"
#include <inttypes.h>
#include <stdint.h>
#include <stdlib.h>
#include <string>
#include <tuple>
#include <utility>
#include "WAVM/Inline/Assert.h"
#include "WAVM/Inline/BasicTypes.h"
#include "WAVM/Inline/CLI.h"
#include "WAVM/Inline/Errors.h"
#include "WAVM/Inline/Timing.h"
#include "WAVM/Logging/Logging.h"
#include "WAVM/NFA/NFA.h"
#include "WAVM/RegExp/RegExp.h"
#include "WAVM/WASTParse/WASTParse.h"

#define DUMP_NFA_GRAPH 0
#define DUMP_DFA_GRAPH 0

using namespace WAVM;
using namespace WAVM::WAST;

namespace WAVM { namespace WAST {
	struct LineInfo
	{
		U32* lineStarts;
		U32 numLineStarts;

		mutable Uptr lastQueryCharOffset{0};
		mutable U32 lastQueryTabs{0};
		mutable U32 lastQueryCharactersAndTabs{0};

		LineInfo(U32* inLineStarts, U32 inNumLineStarts)
		: lineStarts(inLineStarts), numLineStarts(inNumLineStarts)
		{
		}
	};
}}

const char* WAST::describeToken(TokenType tokenType)
{
	static const char* tokenDescriptions[] = {
// This ENUM_TOKENS must come before the literalTokenPairs definition that redefines
// VISIT_OPERATOR_TOKEN.
#define VISIT_TOKEN(name, description, _) description,
		ENUM_TOKENS()
#undef VISIT_TOKEN
	};
	WAVM_ASSERT(tokenType * sizeof(const char*) < sizeof(tokenDescriptions));
	return tokenDescriptions[tokenType];
}

struct StaticData
{
	NFA::Machine nfaMachine;
	StaticData(bool allowLegacyInstructionNames);

	static StaticData& get(bool allowLegacyInstructionNames);
};

static NFA::StateIndex createTokenSeparatorPeekState(NFA::Builder* builder,
													 NFA::StateIndex finalState)
{
	NFA::CharSet tokenSeparatorCharSet;
	tokenSeparatorCharSet.add(U8(' '));
	tokenSeparatorCharSet.add(U8('\t'));
	tokenSeparatorCharSet.add(U8('\r'));
	tokenSeparatorCharSet.add(U8('\n'));
	tokenSeparatorCharSet.add(U8('='));
	tokenSeparatorCharSet.add(U8('('));
	tokenSeparatorCharSet.add(U8(')'));
	tokenSeparatorCharSet.add(U8(';'));
	tokenSeparatorCharSet.add(0);
	auto separatorState = addState(builder);
	NFA::addEdge(builder,
				 separatorState,
				 tokenSeparatorCharSet,
				 finalState | NFA::edgeDoesntConsumeInputFlag);
	return separatorState;
}

static void addLiteralStringToNFA(const char* string,
								  NFA::Builder* builder,
								  NFA::StateIndex initialState,
								  NFA::StateIndex finalState)
{
	// Add the literal to the NFA, one character at a time, reusing existing states that are
	// reachable by the same string.
	for(const char* nextChar = string; *nextChar; ++nextChar)
	{
		NFA::StateIndex nextState = NFA::getNonTerminalEdge(builder, initialState, *nextChar);
		if(nextState < 0 || nextChar[1] == 0)
		{
			nextState = nextChar[1] == 0 ? finalState : addState(builder);
			NFA::addEdge(builder, initialState, NFA::CharSet(*nextChar), nextState);
		}
		initialState = nextState;
	}
}

static void addLiteralTokenToNFA(const char* literalString,
								 NFA::Builder* builder,
								 TokenType tokenType,
								 bool isTokenSeparator)
{
	NFA::StateIndex finalState = NFA::maximumTerminalStateIndex - (NFA::StateIndex)tokenType;
	if(!isTokenSeparator) { finalState = createTokenSeparatorPeekState(builder, finalState); }

	addLiteralStringToNFA(literalString, builder, 0, finalState);
}

StaticData::StaticData(bool allowLegacyInstructionNames)
{
	// clang-format off
static const std::pair<TokenType, const char*> regexpTokenPairs[] = {
	{t_decimalInt, "[+\\-]?\\d+(_\\d+)*"},
	{t_decimalFloat, "[+\\-]?\\d+(_\\d+)*\\.(\\d+(_\\d+)*)*([eE][+\\-]?\\d+(_\\d+)*)?"},
	{t_decimalFloat, "[+\\-]?\\d+(_\\d+)*[eE][+\\-]?\\d+(_\\d+)*"},

	{t_hexInt, "[+\\-]?0[xX][\\da-fA-F]+(_[\\da-fA-F]+)*"},
	{t_hexFloat, "[+\\-]?0[xX][\\da-fA-F]+(_[\\da-fA-F]+)*\\.([\\da-fA-F]+(_[\\da-fA-F]+)*)*([pP][+\\-]?\\d+(_\\d+)*)?"},
	{t_hexFloat, "[+\\-]?0[xX][\\da-fA-F]+(_[\\da-fA-F]+)*[pP][+\\-]?\\d+(_\\d+)*"},

	{t_floatNaN, "[+\\-]?nan(:0[xX][\\da-fA-F]+(_[\\da-fA-F]+)*)?"},
	{t_floatInf, "[+\\-]?inf"},

	{t_string, "\"([^\"\n\\\\]*(\\\\([^0-9a-fA-Fu]|[0-9a-fA-F][0-9a-fA-F]|u\\{[0-9a-fA-F]+})))*\""},

	{t_name, "\\$[a-zA-Z0-9\'_+*/~=<>!?@#$%&|:`.\\-\\^\\\\]+"},
	{t_quotedName, "\\$\"([^\"\n\\\\]*(\\\\([^0-9a-fA-Fu]|[0-9a-fA-F][0-9a-fA-F]|u\\{[0-9a-fA-F]+})))*\""},
};

static const std::tuple<TokenType, const char*, bool> literalTokenTuples[] = {
	std::make_tuple(t_leftParenthesis, "(", true),
	std::make_tuple(t_rightParenthesis, ")", true),
	std::make_tuple(t_equals, "=", true),
	std::make_tuple(t_canonicalNaN, "nan:canonical", false),
	std::make_tuple(t_arithmeticNaN, "nan:arithmetic", false),

	#define VISIT_TOKEN(name, _, literalString) std::make_tuple(t_##name, literalString, false),
	ENUM_LITERAL_TOKENS()
	#undef VISIT_TOKEN

	#undef VISIT_OPERATOR_TOKEN
	#define VISIT_OPERATOR_TOKEN(_, name, nameString, ...) std::make_tuple(t_##name, nameString, false),
	WAVM_ENUM_OPERATORS(VISIT_OPERATOR_TOKEN)
	#undef VISIT_OPERATOR_TOKEN
};

// Legacy aliases for tokens.
static const std::tuple<TokenType, const char*> legacyOperatorAliasTuples[] = {
	std::make_tuple(t_funcref            , "anyfunc"            ),

	std::make_tuple(t_local_get          , "get_local"          ),
	std::make_tuple(t_local_set          , "set_local"          ),
	std::make_tuple(t_local_tee          , "tee_local"          ),
	std::make_tuple(t_global_get         , "get_global"         ),
	std::make_tuple(t_global_set         , "set_global"         ),

	std::make_tuple(t_i32_wrap_i64       , "i32.wrap/i64"       ),
	std::make_tuple(t_i32_trunc_f32_s    , "i32.trunc_s/f32"    ),
	std::make_tuple(t_i32_trunc_f32_u    , "i32.trunc_u/f32"    ),
	std::make_tuple(t_i32_trunc_f64_s    , "i32.trunc_s/f64"    ),
	std::make_tuple(t_i32_trunc_f64_u    , "i32.trunc_u/f64"    ),
	std::make_tuple(t_i64_extend_i32_s   , "i64.extend_s/i32"   ),
	std::make_tuple(t_i64_extend_i32_u   , "i64.extend_u/i32"   ),
	std::make_tuple(t_i64_trunc_f32_s    , "i64.trunc_s/f32"    ),
	std::make_tuple(t_i64_trunc_f32_u    , "i64.trunc_u/f32"    ),
	std::make_tuple(t_i64_trunc_f64_s    , "i64.trunc_s/f64"    ),
	std::make_tuple(t_i64_trunc_f64_u    , "i64.trunc_u/f64"    ),
	std::make_tuple(t_f32_convert_i32_s  , "f32.convert_s/i32"  ),
	std::make_tuple(t_f32_convert_i32_u  , "f32.convert_u/i32"  ),
	std::make_tuple(t_f32_convert_i64_s  , "f32.convert_s/i64"  ),
	std::make_tuple(t_f32_convert_i64_u  , "f32.convert_u/i64"  ),
	std::make_tuple(t_f32_demote_f64     , "f32.demote/f64"     ),
	std::make_tuple(t_f64_convert_i32_s  , "f64.convert_s/i32"  ),
	std::make_tuple(t_f64_convert_i32_u  , "f64.convert_u/i32"  ),
	std::make_tuple(t_f64_convert_i64_s  , "f64.convert_s/i64"  ),
	std::make_tuple(t_f64_convert_i64_u  , "f64.convert_u/i64"  ),
	std::make_tuple(t_f64_promote_f32    , "f64.promote/f32"    ),
	std::make_tuple(t_i32_reinterpret_f32, "i32.reinterpret/f32"),
	std::make_tuple(t_i64_reinterpret_f64, "i64.reinterpret/f64"),
	std::make_tuple(t_f32_reinterpret_i32, "f32.reinterpret/i32"),
	std::make_tuple(t_f64_reinterpret_i64, "f64.reinterpret/i64")
};
	// clang-format on

	Timing::Timer timer;

	NFA::Builder* nfaBuilder = NFA::createBuilder();

	for(auto regexpTokenPair : regexpTokenPairs)
	{
		NFA::StateIndex finalState
			= NFA::maximumTerminalStateIndex - (NFA::StateIndex)regexpTokenPair.first;
		finalState = createTokenSeparatorPeekState(nfaBuilder, finalState);
		RegExp::addToNFA(regexpTokenPair.second, nfaBuilder, 0, finalState);
	}

	for(auto literalTokenTuple : literalTokenTuples)
	{
		const TokenType tokenType = std::get<0>(literalTokenTuple);
		const char* literalString = std::get<1>(literalTokenTuple);
		const bool isTokenSeparator = std::get<2>(literalTokenTuple);
		addLiteralTokenToNFA(literalString, nfaBuilder, tokenType, isTokenSeparator);
	}

	for(auto legacyOperatorAliasTuple : legacyOperatorAliasTuples)
	{
		const TokenType tokenType = allowLegacyInstructionNames
										? std::get<0>(legacyOperatorAliasTuple)
										: TokenType(t_legacyInstructionName);
		const char* literalString = std::get<1>(legacyOperatorAliasTuple);
		addLiteralTokenToNFA(literalString, nfaBuilder, tokenType, false);
	}

	if(DUMP_NFA_GRAPH)
	{
		std::string nfaGraphVizString = NFA::dumpNFAGraphViz(nfaBuilder);
		WAVM_ERROR_UNLESS(
			saveFile("nfaGraph.dot", nfaGraphVizString.data(), nfaGraphVizString.size()));
	}

	nfaMachine = NFA::Machine(nfaBuilder);

	if(DUMP_DFA_GRAPH)
	{
		std::string dfaGraphVizString = nfaMachine.dumpDFAGraphViz();
		WAVM_ERROR_UNLESS(
			saveFile("dfaGraph.dot", dfaGraphVizString.data(), dfaGraphVizString.size()));
	}

	Timing::logTimer("built lexer tables", timer);
}

StaticData& StaticData::get(bool allowLegacyInstructionNames)
{
	if(allowLegacyInstructionNames)
	{
		static StaticData staticData(true);
		return staticData;
	}
	else
	{
		static StaticData staticData(false);
		return staticData;
	}
}

inline bool isRecoveryPointChar(char c)
{
	switch(c)
	{
	// Recover lexing at the next whitespace or parenthesis.
	case ' ':
	case '\t':
	case '\r':
	case '\n':
	case '\f':
	case '(':
	case ')': return true;
	default: return false;
	};
}

Token* WAST::lex(const char* string,
				 Uptr stringLength,
				 LineInfo*& outLineInfo,
				 bool allowLegacyInstructionNames)
{
	WAVM_ERROR_UNLESS(string);
	WAVM_ERROR_UNLESS(string[stringLength - 1] == 0);

	StaticData& staticData = StaticData::get(allowLegacyInstructionNames);

	Timing::Timer timer;

	if(stringLength > UINT32_MAX)
	{ Errors::fatalf("cannot lex strings with more than %u characters", UINT32_MAX); }

	// Allocate enough memory up front for a token and newline for each character in the input
	// string.
	Token* tokens = (Token*)malloc(sizeof(Token) * (stringLength + 1));
	U32* lineStarts = (U32*)malloc(sizeof(U32) * (stringLength + 2));

	Token* nextToken = tokens;
	U32* nextLineStart = lineStarts;
	*nextLineStart++ = 0;

	const char* nextChar = string;
	while(true)
	{
		// Skip whitespace and comments (keeping track of newlines).
		while(true)
		{
			switch(*nextChar)
			{
			// Single line comments.
			case ';':
				if(nextChar[1] != ';') { goto doneSkippingWhitespace; }
				else
				{
					nextChar += 2;
					while(*nextChar)
					{
						if(*nextChar == '\n')
						{
							// Emit a line start for the newline.
							*nextLineStart++ = U32(nextChar - string + 1);
							++nextChar;
							break;
						}
						++nextChar;
					};
				}
				break;
			// Delimited (possibly multi-line) comments.
			case '(':
				if(nextChar[1] != ';') { goto doneSkippingWhitespace; }
				else
				{
					const char* firstCommentChar = nextChar;
					nextChar += 2;
					U32 commentDepth = 1;
					while(commentDepth)
					{
						if(nextChar[0] == ';' && nextChar[1] == ')')
						{
							--commentDepth;
							nextChar += 2;
						}
						else if(nextChar[0] == '(' && nextChar[1] == ';')
						{
							++commentDepth;
							nextChar += 2;
						}
						else if(nextChar == string + stringLength - 1)
						{
							// Emit an unterminated comment token.
							nextToken->type = t_unterminatedComment;
							nextToken->begin = U32(firstCommentChar - string);
							++nextToken;
							goto doneSkippingWhitespace;
						}
						else
						{
							if(*nextChar == '\n')
							{
								// Emit a line start for the newline.
								*nextLineStart++ = U32(nextChar - string);
							}
							++nextChar;
						}
					};
				}
				break;
			// Whitespace.
			case '\n':
				*nextLineStart++ = U32(nextChar - string + 1);
				++nextChar;
				break;
			case ' ':
			case '\t':
			case '\r':
			case '\f': ++nextChar; break;
			default: goto doneSkippingWhitespace;
			};
		}
	doneSkippingWhitespace:

		// Once we reach a non-whitespace, non-comment character, feed characters into the NFA
		// until it reaches a terminal state.
		nextToken->begin = U32(nextChar - string);
		NFA::StateIndex terminalState = staticData.nfaMachine.feed(nextChar);
		if(terminalState != NFA::unmatchedCharacterTerminal)
		{
			nextToken->type
				= TokenType(NFA::maximumTerminalStateIndex - (NFA::StateIndex)terminalState);
			++nextToken;
		}
		else
		{
			if(nextToken->begin < stringLength - 1)
			{
				// Emit an unrecognized token.
				nextToken->type = t_unrecognized;
				++nextToken;

				// Advance until a recovery point or the end of the string.
				const char* stringEnd = string + stringLength - 1;
				while(nextChar < stringEnd && !isRecoveryPointChar(*nextChar)) { ++nextChar; }
			}
			else
			{
				break;
			}
		}
	}

	// Emit an end token to mark the end of the token stream.
	nextToken->type = t_eof;
	++nextToken;

	// Emit an extra line start for the end of the file, so you can find the end of a line with
	// lineStarts[line + 1].
	*nextLineStart++ = U32(nextChar - string) + 1;

	// Shrink the line start and token arrays to the final number of tokens/lines.
	const Uptr numLineStarts = nextLineStart - lineStarts;
	const Uptr numTokens = nextToken - tokens;
	lineStarts = (U32*)realloc(lineStarts, sizeof(U32) * numLineStarts);
	tokens = (Token*)realloc(tokens, sizeof(Token) * numTokens);

	// Create the LineInfo object that encapsulates the line start information.
	outLineInfo = new LineInfo{lineStarts, U32(numLineStarts)};

	Timing::logRatePerSecond("lexed WAST file", timer, stringLength / 1024.0 / 1024.0, "MiB");
	Log::printf(Log::metrics,
				"lexer produced %" WAVM_PRIuPTR " tokens (%.1fMiB)\n",
				numTokens,
				numTokens * sizeof(Token) / 1024.0 / 1024.0);

	return tokens;
}

void WAST::freeTokens(Token* tokens) { free(tokens); }

void WAST::freeLineInfo(LineInfo* lineInfo)
{
	free(lineInfo->lineStarts);
	delete lineInfo;
}

static Uptr getLineOffset(const LineInfo* lineInfo, Uptr lineIndex)
{
	WAVM_ERROR_UNLESS(lineIndex < lineInfo->numLineStarts);
	return lineInfo->lineStarts[lineIndex];
}

TextFileLocus WAST::calcLocusFromOffset(const char* string,
										const LineInfo* lineInfo,
										Uptr charOffset)
{
	// The last line start is at the end of the string, so use it to sanity check that the
	// charOffset isn't past the end of the string.
	const Uptr numChars = lineInfo->lineStarts[lineInfo->numLineStarts - 1];
	WAVM_ASSERT(charOffset <= numChars);

	// Binary search the line starts for the last one before charIndex.
	Uptr minLineIndex = 0;
	Uptr maxLineIndex = lineInfo->numLineStarts - 1;
	while(maxLineIndex > minLineIndex)
	{
		const Uptr medianLineIndex = (minLineIndex + maxLineIndex + 1) / 2;
		if(charOffset < lineInfo->lineStarts[medianLineIndex])
		{ maxLineIndex = medianLineIndex - 1; }
		else if(charOffset > lineInfo->lineStarts[medianLineIndex])
		{
			minLineIndex = medianLineIndex;
		}
		else
		{
			minLineIndex = maxLineIndex = medianLineIndex;
		}
	};
	TextFileLocus result;
	result.newlines = (U32)minLineIndex;

	// Calculate the offsets to the start and end of the line containing the locus.
	result.lineStartOffset = getLineOffset(lineInfo, result.newlines);
	result.lineEndOffset = getLineOffset(lineInfo, result.newlines + 1) - 1;
	WAVM_ASSERT(charOffset >= result.lineStartOffset);
	WAVM_ASSERT(charOffset <= result.lineEndOffset);

	// Try to reuse work done by the last query counting characters on this line. Without this
	// reuse, it's possible to craft an input that takes O(numChars^2) time to parse: an input with
	// a single line with O(numChars) errors will take O(numChars) time to count the tabs+characters
	// preceding the error on the line *for each error*.
	const char* nextChar = string + result.lineStartOffset;
	if(lineInfo->lastQueryCharOffset < charOffset
	   && lineInfo->lastQueryCharOffset > result.lineStartOffset)
	{
		nextChar = string + lineInfo->lastQueryCharOffset;
		result.tabs = lineInfo->lastQueryTabs;
	}

	// Count tabs from the beginning of the line to locus.
	while(nextChar < string + charOffset)
	{
		result.tabs += *nextChar == '\t' ? 1 : 0;
		++nextChar;
	}

	// Derive the number of non-tab characters from the offset within the line and the number of
	// tabs preceding this locus in the line.
	result.characters = U32(charOffset - result.lineStartOffset - result.tabs);

	lineInfo->lastQueryCharOffset = charOffset;
	lineInfo->lastQueryTabs = result.tabs;

	return result;
}