-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompiler_Lexer.H
More file actions
635 lines (571 loc) · 19.3 KB
/
Copy pathCompiler_Lexer.H
File metadata and controls
635 lines (571 loc) · 19.3 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
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
/*
Aleph_w
Data structures & Algorithms
version 2.0.0b
https://github.com/lrleon/Aleph-w
This file is part of Aleph-w library
Copyright (c) 2002-2026 Leandro Rabindranath Leon
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.
*/
/** @file Compiler_Lexer.H
* @brief Lexical analyzer (Lexer) based on `Source_Manager`.
*
* The lexer is the first component of the front-end. Its mission is to transform
* a stream of characters from a source file into a sequence of `Compiler_Token`
* objects with semantic meaning.
*
* ### Responsibilities:
* - Skip whitespace and (optionally) comments.
* - Classify identifiers and keywords.
* - Parse numeric, string, and character literals, managing escape sequences.
* - Emit readable diagnostics for lexical errors (e.g., unterminated strings).
*
* ### Typical Usage:
* @code
* Compiler_Lexer lexer(source_manager, file_id, diag_engine);
* while (!lexer.eof()) {
* Compiler_Token tok = lexer.next();
* // Process token...
* }
* @endcode
*
* @ingroup Utilities
*/
#ifndef COMPILER_LEXER_H
#define COMPILER_LEXER_H
#include <cctype>
#include <string>
#include <Compiler_Token.H>
#include <ah-diagnostics.H>
namespace Aleph {
/** @brief Configuration options for lexer behavior.
*
* Allows adjusting which parts of the source code are ignored and which
* comment rules apply.
*
* @note Thread-safety: Thread-safe (POD).
* @note Complexity: O(1).
*/
struct Compiler_Lexer_Options
{
bool keep_comments = false; ///< If true, comments are returned as tokens.
bool allow_block_comments = true; ///< If false, `/*` is treated as `/` followed by `*`.
};
/** @brief Token generator for a single source file.
*
* Maintains the reading state (cursor) and provides a "consumption" interface
* for logical symbols.
*
* @note Thread-safety: Not thread-safe. Each file should have its own lexer
* instance if processed in parallel.
*/
class Compiler_Lexer
{
const Source_Manager *sources_ = nullptr;
Source_File_Id file_id_ = 0;
const std::string *input_ = nullptr;
Diagnostic_Engine *diagnostics_ = nullptr;
Compiler_Lexer_Options options_;
Source_Offset cursor_ = 0;
bool has_lookahead_ = false;
Compiler_Token lookahead_;
/** @brief Checks if a character can start an identifier. */
static bool is_ident_start(const unsigned char ch) noexcept
{
return std::isalpha(ch) or ch == '_';
}
/** @brief Checks if a character can continue an identifier. */
static bool is_ident_continue(const unsigned char ch) noexcept
{
return std::isalnum(ch) or ch == '_';
}
/** @brief Returns true if the cursor has reached the end of the input. */
[[nodiscard]] bool at_end() const noexcept
{
return cursor_ >= input_->size();
}
/** @brief Safe character access at a given offset. */
[[nodiscard]] char char_at(const Source_Offset off) const noexcept
{
return off < input_->size() ? (*input_)[off] : '\0';
}
/** @brief Returns the character at the current cursor position. */
[[nodiscard]] char current_char() const noexcept
{
return char_at(cursor_);
}
/** @brief Returns the character following the current cursor position. */
[[nodiscard]] char next_char() const noexcept
{
return char_at(cursor_ + 1);
}
/** @brief Creates a source span for the given range in the current file. */
[[nodiscard]] Source_Span make_span(const Source_Offset begin, const Source_Offset end) const
{
return sources_->span(file_id_, begin, end);
}
/** @brief Creates a token with the given kind and range. */
[[nodiscard]] Compiler_Token make_token(const Compiler_Token_Kind kind,
const Source_Offset begin,
const Source_Offset end) const
{
const auto sp = make_span(begin, end);
return {kind, sources_->slice(sp), sp};
}
/** @brief Creates an End_Of_File token at the current position. */
[[nodiscard]] Compiler_Token make_eof_token() const
{
const auto sp = make_span(cursor_, cursor_);
return {Compiler_Token_Kind::End_Of_File, "", sp};
}
/** @brief Emits a diagnostic error through the engine. */
void emit_error(const Source_Span &span,
const std::string &message,
const std::string &code,
const std::string ¬e = "",
const std::string &help = "") const
{
if (diagnostics_ == nullptr)
return;
auto builder = diagnostics_->error(span, message).code(code);
if (not note.empty())
builder.note(note);
if (not help.empty())
builder.help(help);
builder.emit();
}
/** @brief Consumes whitespace characters. */
void skip_whitespace()
{
while (not at_end() and std::isspace(static_cast<unsigned char>(current_char())))
++cursor_;
}
/** @brief Lexes a single-line comment. */
Compiler_Token lex_line_comment()
{
const Source_Offset begin = cursor_;
cursor_ += 2;
while (not at_end() and current_char() != '\n')
++cursor_;
return make_token(Compiler_Token_Kind::Line_Comment, begin, cursor_);
}
/** @brief Lexes a multi-line block comment. */
Compiler_Token lex_block_comment()
{
const Source_Offset begin = cursor_;
cursor_ += 2;
while (not at_end())
{
if (current_char() == '*' and next_char() == '/')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::Block_Comment, begin, cursor_);
}
++cursor_;
}
const auto sp = make_span(begin, cursor_);
emit_error(sp, "unterminated block comment", "LEX004", "block comments must end with '*/'");
return {Compiler_Token_Kind::Invalid, sources_->slice(sp), sp};
}
/** @brief Lexes an identifier or classifies it as a keyword. */
Compiler_Token lex_identifier_or_keyword()
{
const Source_Offset begin = cursor_;
++cursor_;
while (not at_end() and is_ident_continue(static_cast<unsigned char>(current_char())))
++cursor_;
const auto sp = make_span(begin, cursor_);
const auto lexeme = sources_->slice(sp);
return {classify_compiler_keyword(lexeme), lexeme, sp};
}
/** @brief Lexes a numeric literal. */
Compiler_Token lex_number()
{
const Source_Offset begin = cursor_;
++cursor_;
while (not at_end())
{
const auto ch = static_cast<unsigned char>(current_char());
if (std::isdigit(ch))
{
++cursor_;
continue;
}
if (ch == '_' and std::isdigit(static_cast<unsigned char>(next_char())))
{
++cursor_;
continue;
}
break;
}
return make_token(Compiler_Token_Kind::Integer_Literal, begin, cursor_);
}
/** @brief Lexes a string literal. */
Compiler_Token lex_string()
{
const Source_Offset begin = cursor_;
++cursor_;
while (not at_end())
{
const char ch = current_char();
if (ch == '"')
{
++cursor_;
return make_token(Compiler_Token_Kind::String_Literal, begin, cursor_);
}
if (ch == '\\')
{
++cursor_;
if (at_end())
break;
++cursor_;
continue;
}
if (ch == '\n' or ch == '\r')
break;
++cursor_;
}
const auto sp = make_span(begin, cursor_);
emit_error(sp,
"unterminated string literal",
"LEX002",
"string literal started here",
"close the string with a double quote");
return {Compiler_Token_Kind::Invalid, sources_->slice(sp), sp};
}
/** @brief Lexes a character literal. */
Compiler_Token lex_char_literal()
{
const Source_Offset begin = cursor_;
++cursor_;
if (at_end() or current_char() == '\n' or current_char() == '\r')
{
const auto sp = make_span(begin, cursor_);
emit_error(sp, "unterminated character literal", "LEX003", "character literal started here");
return {Compiler_Token_Kind::Invalid, sources_->slice(sp), sp};
}
if (current_char() == '\\')
{
++cursor_;
if (at_end() or current_char() == '\n' or current_char() == '\r')
{
const auto sp = make_span(begin, cursor_);
emit_error(sp, "unterminated escape sequence in character literal", "LEX003");
return {Compiler_Token_Kind::Invalid, sources_->slice(sp), sp};
}
++cursor_;
}
else
++cursor_;
if (not at_end() and current_char() == '\'')
{
++cursor_;
return make_token(Compiler_Token_Kind::Char_Literal, begin, cursor_);
}
while (not at_end() and current_char() != '\'' and current_char() != '\n'
and current_char() != '\r')
++cursor_;
if (not at_end() and current_char() == '\'')
++cursor_;
const auto sp = make_span(begin, cursor_);
emit_error(sp,
"malformed character literal",
"LEX003",
"character literals must contain exactly one character or escape");
return {Compiler_Token_Kind::Invalid, sources_->slice(sp), sp};
}
/** @brief Lexes punctuation or operator symbols. */
Compiler_Token lex_punctuation_or_operator()
{
const Source_Offset begin = cursor_;
const char a = current_char();
const char b = next_char();
// Multicharacter operators/punctuation
if (a == ':' and b == ':')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::Double_Colon, begin, cursor_);
}
if (a == '-' and b == '>')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::Arrow, begin, cursor_);
}
if (a == '=' and b == '=')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::EqEq, begin, cursor_);
}
if (a == '!' and b == '=')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::NotEq, begin, cursor_);
}
if (a == '<' and b == '=')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::LessEq, begin, cursor_);
}
if (a == '>' and b == '=')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::GreaterEq, begin, cursor_);
}
if (a == '&' and b == '&')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::AndAnd, begin, cursor_);
}
if (a == '|' and b == '|')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::OrOr, begin, cursor_);
}
if (a == '+' and b == '=')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::PlusEq, begin, cursor_);
}
if (a == '-' and b == '=')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::MinusEq, begin, cursor_);
}
if (a == '*' and b == '=')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::StarEq, begin, cursor_);
}
if (a == '/' and b == '=')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::SlashEq, begin, cursor_);
}
if (a == '%' and b == '=')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::PercentEq, begin, cursor_);
}
if (a == '+' and b == '+')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::PlusPlus, begin, cursor_);
}
if (a == '-' and b == '-')
{
cursor_ += 2;
return make_token(Compiler_Token_Kind::MinusMinus, begin, cursor_);
}
++cursor_;
switch (a)
{
case '(':
return make_token(Compiler_Token_Kind::LParen, begin, cursor_);
case ')':
return make_token(Compiler_Token_Kind::RParen, begin, cursor_);
case '{':
return make_token(Compiler_Token_Kind::LBrace, begin, cursor_);
case '}':
return make_token(Compiler_Token_Kind::RBrace, begin, cursor_);
case '[':
return make_token(Compiler_Token_Kind::LBracket, begin, cursor_);
case ']':
return make_token(Compiler_Token_Kind::RBracket, begin, cursor_);
case ',':
return make_token(Compiler_Token_Kind::Comma, begin, cursor_);
case '.':
return make_token(Compiler_Token_Kind::Dot, begin, cursor_);
case ':':
return make_token(Compiler_Token_Kind::Colon, begin, cursor_);
case ';':
return make_token(Compiler_Token_Kind::Semicolon, begin, cursor_);
case '?':
return make_token(Compiler_Token_Kind::Question, begin, cursor_);
case '=':
return make_token(Compiler_Token_Kind::Assign, begin, cursor_);
case '+':
return make_token(Compiler_Token_Kind::Plus, begin, cursor_);
case '-':
return make_token(Compiler_Token_Kind::Minus, begin, cursor_);
case '*':
return make_token(Compiler_Token_Kind::Star, begin, cursor_);
case '/':
return make_token(Compiler_Token_Kind::Slash, begin, cursor_);
case '%':
return make_token(Compiler_Token_Kind::Percent, begin, cursor_);
case '&':
return make_token(Compiler_Token_Kind::Amp, begin, cursor_);
case '|':
return make_token(Compiler_Token_Kind::Pipe, begin, cursor_);
case '^':
return make_token(Compiler_Token_Kind::Caret, begin, cursor_);
case '!':
return make_token(Compiler_Token_Kind::Bang, begin, cursor_);
case '~':
return make_token(Compiler_Token_Kind::Tilde, begin, cursor_);
case '<':
return make_token(Compiler_Token_Kind::Less, begin, cursor_);
case '>':
return make_token(Compiler_Token_Kind::Greater, begin, cursor_);
default:
{
const auto sp = make_span(begin, cursor_);
emit_error(sp, std::string("unexpected character '") + a + "'", "LEX001");
return {Compiler_Token_Kind::Invalid, sources_->slice(sp), sp};
}
}
}
/** @brief Dispatches the next token from the input stream. */
Compiler_Token lex_token()
{
while (true)
{
skip_whitespace();
if (at_end())
return make_eof_token();
if (current_char() == '/' and next_char() == '/')
{
if (auto tok = lex_line_comment(); options_.keep_comments or tok.is_invalid())
return tok;
continue;
}
if (options_.allow_block_comments and current_char() == '/' and next_char() == '*')
{
if (auto tok = lex_block_comment(); options_.keep_comments or tok.is_invalid())
return tok;
continue;
}
break;
}
const auto ch = static_cast<unsigned char>(current_char());
if (is_ident_start(ch))
return lex_identifier_or_keyword();
if (std::isdigit(ch))
return lex_number();
if (current_char() == '"')
return lex_string();
if (current_char() == '\'')
return lex_char_literal();
return lex_punctuation_or_operator();
}
public:
/** @brief Initializes a lexer for a registered source file.
*
* @param sm Source manager containing the file text.
* @param id Identifier of the file to tokenize.
* @param dx Diagnostic engine to report errors. If null, errors are only
* indicated via `Invalid` tokens.
* @param opts Trivia handling options (comments, etc.).
* @throws std::out_of_range If `id` is not valid in `sm`.
* @note Thread-safety: Not thread-safe.
* @note Complexity: O(1).
*/
Compiler_Lexer(const Source_Manager &sm,
const Source_File_Id id,
Diagnostic_Engine *dx = nullptr,
const Compiler_Lexer_Options &opts = {})
: sources_(&sm), file_id_(id), input_(&sm.file_text(id)), diagnostics_(dx), options_(opts)
{}
/** @brief Returns the file ID currently being analyzed.
*
* @return The stable ID associated with this lexer.
* @note Thread-safety: Safe for concurrent readers.
* @note Complexity: O(1).
*/
[[nodiscard]] Source_File_Id source_file_id() const noexcept
{
return file_id_;
}
/** @brief Returns the current byte offset in the file.
*
* Useful for saving recovery states or for telemetry.
*
* @return Cursor position in bytes.
* @note Thread-safety: Safe for concurrent readers.
* @note Complexity: O(1).
*/
[[nodiscard]] Source_Offset current_offset() const noexcept
{
return cursor_;
}
/** @brief Repositions the reading cursor.
*
* Discards any pre-read tokens (lookahead) and restarts the analysis
* from the indicated position.
*
* @param offset New byte offset (default 0, the beginning).
* @throws std::out_of_range If the offset exceeds the file length.
* @note Thread-safety: Not thread-safe.
* @note Complexity: O(1).
*/
void reset(const Source_Offset offset = 0)
{
ah_out_of_range_error_unless(offset <= input_->size())
<< "Compiler_Lexer::reset(): invalid offset " << offset;
cursor_ = offset;
has_lookahead_ = false;
lookahead_ = Compiler_Token();
}
/** @brief Peeks at the next token without advancing the cursor.
*
* Allows the parser to make syntactic decisions based on the next symbol
* without consuming it permanently. Successive calls return the same token.
*
* @return The next available token in the stream.
* @note Thread-safety: Not thread-safe.
* @note Complexity: O(N) where N is lexeme length (amortized).
*/
const Compiler_Token &peek()
{
if (not has_lookahead_)
{
lookahead_ = lex_token();
has_lookahead_ = true;
}
return lookahead_;
}
/** @brief Consumes and returns the next token from the stream.
*
* Advances the internal cursor. If there is a lexical error, returns an
* `Invalid` token but continues advancing to attempt recovery.
*
* @return The consumed token.
* @note Thread-safety: Not thread-safe.
* @note Complexity: O(N) where N is lexeme length (amortized).
*/
Compiler_Token next()
{
if (has_lookahead_)
{
has_lookahead_ = false;
return lookahead_;
}
return lex_token();
}
/** @brief Indicates whether the end of the file has been reached.
*
* @return `true` if the next call to `next()` would return `End_Of_File`.
* @note Thread-safety: Not thread-safe.
* @note Complexity: O(N) (calls peek internally).
*/
bool eof()
{
return peek().is_eof();
}
};
} // namespace Aleph
#endif // COMPILER_LEXER_H