forked from sorbet/sorbet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lexer.rl
2877 lines (2425 loc) · 78.5 KB
/
lexer.rl
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2013-2016 whitequark <whitequark@whitequark.org>
Parts of the source are derived from ruby_parser:
Copyright (c) Ryan Davis, seattle.rb
This lexer is a rewrite of the original in Ragel/C:
Copyright (c) Charlie Somerville, GitHub
MIT License
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.
*/
%%machine lex; # % fix highlighting
/*
#
# === BEFORE YOU START ===
#
# Read the Ruby Hacking Guide chapter 11, available in English at
# http://whitequark.org/blog/2013/04/01/ruby-hacking-guide-ch-11-finite-state-lexer/
#
# Remember two things about Ragel scanners:
#
# 1) Longest match wins.
#
# 2) If two matches have the same length, the first
# in source code wins.
#
# General rules of making Ragel and Bison happy:
#
# * `p` (position) and `@te` contain the index of the character
# they're pointing to ("current"), plus one. `@ts` contains the index
# of the corresponding character. The code for extracting matched token is:
#
# @source_buffer.slice(@ts...@te)
#
# * If your input is `foooooooobar` and the rule is:
#
# 'f' 'o'+
#
# the result will be:
#
# foooooooobar
# ^ ts=0 ^ p=te=9
#
# * A Ragel lexer action should not emit more than one token, unless
# you know what you are doing.
#
# * All Ragel commands (fnext, fgoto, ...) end with a semicolon.
#
# * If an action emits the token and transitions to another state, use
# these Ragel commands:
#
# emit($whatever)
# fnext $next_state; fbreak;
#
# If you perform `fgoto` in an action which does not emit a token nor
# rewinds the stream pointer, the parser's side-effectful,
# context-sensitive lookahead actions will break in a hard to detect
# and debug way.
#
# * If an action does not emit a token:
#
# fgoto $next_state;
#
# * If an action features lookbehind, i.e. matches characters with the
# intent of passing them to another action:
#
# p = @ts - 1
# fgoto $next_state;
#
# or, if the lookbehind consists of a single character:
#
# fhold; fgoto $next_state;
#
# * Ragel merges actions. So, if you have `e_lparen = '(' %act` and
# `c_lparen = '('` and a lexer action `e_lparen | c_lparen`, the result
# _will_ invoke the action `act`.
#
# e_something stands for "something with **e**mbedded action".
#
# * EOF is explicit and is matched by `c_eof`. If you want to introspect
# the state of the lexer, add this rule to the state:
#
# c_eof => do_eof;
#
# * If you proceed past EOF, the lexer will complain:
#
# NoMethodError: undefined method `ord' for nil:NilClass
#
*/
#include <ruby_parser/driver.hh>
#include <cassert>
#include "absl/strings/numbers.h"
%% write data nofinal;
using namespace ruby_parser;
using namespace std::string_literals;
%% prepush { check_stack_capacity(); }
lexer::lexer(diagnostics_t &diag, ruby_version version, const std::string& source_buffer_)
: diagnostics(diag)
, version(version)
, source_buffer(source_buffer_ + std::string("\0\0", 2))
, cs(lex_en_line_begin)
, _p(source_buffer.data())
, _pe(source_buffer.data() + source_buffer.size())
, ts(nullptr)
, te(nullptr)
, act(0)
, top(0)
, eq_begin_s(nullptr)
, sharp_s(nullptr)
, newline_s(nullptr)
, paren_nest(0)
, command_start(true)
, num_base(0)
, num_digits_s(nullptr)
, num_suffix_s(nullptr)
, num_xfrm(num_xfrm_type::NONE)
, escape_s(nullptr)
, herebody_s(nullptr)
, in_kwarg(false)
{
// ensure the stack is non-empty so we can just double in
// check_stack_capacity:
stack.resize(16);
static_env.push(environment());
cs_before_block_comment = lex_en_line_begin;
}
void lexer::check_stack_capacity() {
if (stack.size() == (size_t)top) {
stack.resize(stack.size() * 2);
}
}
int lexer::stack_pop() {
return stack[--top];
}
int lexer::arg_or_cmdarg(int cmd_state) {
if (cmd_state) {
return lex_en_expr_cmdarg;
} else {
return lex_en_expr_arg;
}
}
void lexer::emit_comment(const char* s, const char* e) {
/* unused for now */
(void)s;
(void)e;
}
std::string lexer::tok() {
return tok(ts);
}
std::string lexer::tok(const char* start) {
return tok(start, te);
}
std::string lexer::tok(const char* start, const char* end) {
assert(start <= end);
return std::string(start, (size_t)(end - start));
}
char lexer::unescape(uint32_t codepoint) {
switch (codepoint) {
case 'a': return '\a';
case 'b': return '\b';
case 'e': return 0x1b;
case 'f': return '\f';
case 'n': return '\n';
case 'r': return '\r';
case 's': return ' ';
case 't': return '\t';
case 'v': return '\v';
case '\\': return '\\';
default: return '\0';
}
}
static const lexer::token_table_entry PUNCTUATION[] = {
{ "=", token_type::tEQL },
{ "&", token_type::tAMPER2 },
{ "|", token_type::tPIPE },
{ "!", token_type::tBANG },
{ "^", token_type::tCARET },
{ "+", token_type::tPLUS },
{ "-", token_type::tMINUS },
{ "*", token_type::tSTAR2 },
{ "/", token_type::tDIVIDE },
{ "%", token_type::tPERCENT },
{ "~", token_type::tTILDE },
{ ",", token_type::tCOMMA },
{ ";", token_type::tSEMI },
{ ".", token_type::tDOT },
{ "..", token_type::tDOT2 },
{ "...", token_type::tDOT3 },
{ "[", token_type::tLBRACK2 },
{ "]", token_type::tRBRACK },
{ "(", token_type::tLPAREN2 },
{ ")", token_type::tRPAREN },
{ "?", token_type::tEH },
{ ":", token_type::tCOLON },
{ "&&", token_type::tANDOP },
{ "||", token_type::tOROP },
{ "-@", token_type::tUMINUS },
{ "+@", token_type::tUPLUS },
{ "~@", token_type::tTILDE },
{ "**", token_type::tPOW },
{ "->", token_type::tLAMBDA },
{ "=~", token_type::tMATCH },
{ "!~", token_type::tNMATCH },
{ "==", token_type::tEQ },
{ "!=", token_type::tNEQ },
{ ">", token_type::tGT },
{ ">>", token_type::tRSHFT },
{ ">=", token_type::tGEQ },
{ "<", token_type::tLT },
{ "<<", token_type::tLSHFT },
{ "<=", token_type::tLEQ },
{ "=>", token_type::tASSOC },
{ "::", token_type::tCOLON2 },
{ "===", token_type::tEQQ },
{ "<=>", token_type::tCMP },
{ "[]", token_type::tAREF },
{ "[]=", token_type::tASET },
{ "{", token_type::tLCURLY },
{ "}", token_type::tRCURLY },
{ "`", token_type::tBACK_REF2 },
{ "!@", token_type::tBANG },
{ "&.", token_type::tANDDOT },
{ NULL, token_type::error },
};
static const lexer::token_table_entry PUNCTUATION_BEGIN[] = {
{ "&", token_type::tAMPER },
{ "*", token_type::tSTAR },
{ "**", token_type::tDSTAR },
{ "+", token_type::tUPLUS },
{ "-", token_type::tUMINUS },
{ "::", token_type::tCOLON3 },
{ "(", token_type::tLPAREN },
{ "{", token_type::tLBRACE },
{ "[", token_type::tLBRACK },
{ NULL, token_type::error },
};
static const lexer::token_table_entry KEYWORDS[] = {
{ "if", token_type::kIF_MOD },
{ "unless", token_type::kUNLESS_MOD },
{ "while", token_type::kWHILE_MOD },
{ "until", token_type::kUNTIL_MOD },
{ "rescue", token_type::kRESCUE_MOD },
{ "defined?", token_type::kDEFINED },
{ "BEGIN", token_type::klBEGIN },
{ "END", token_type::klEND },
{ "class", token_type::kCLASS },
{ "module", token_type::kMODULE },
{ "def", token_type::kDEF },
{ "undef", token_type::kUNDEF },
{ "begin", token_type::kBEGIN },
{ "end", token_type::kEND },
{ "then", token_type::kTHEN },
{ "elsif", token_type::kELSIF },
{ "else", token_type::kELSE },
{ "ensure", token_type::kENSURE },
{ "case", token_type::kCASE },
{ "when", token_type::kWHEN },
{ "for", token_type::kFOR },
{ "break", token_type::kBREAK },
{ "next", token_type::kNEXT },
{ "redo", token_type::kREDO },
{ "retry", token_type::kRETRY },
{ "in", token_type::kIN },
{ "do", token_type::kDO },
{ "return", token_type::kRETURN },
{ "yield", token_type::kYIELD },
{ "super", token_type::kSUPER },
{ "self", token_type::kSELF },
{ "nil", token_type::kNIL },
{ "true", token_type::kTRUE },
{ "false", token_type::kFALSE },
{ "and", token_type::kAND },
{ "or", token_type::kOR },
{ "not", token_type::kNOT },
{ "alias", token_type::kALIAS },
{ "__FILE__", token_type::k__FILE__ },
{ "__LINE__", token_type::k__LINE__ },
{ "__ENCODING__", token_type::k__ENCODING__ },
{ NULL, token_type::error },
};
static const lexer::token_table_entry KEYWORDS_BEGIN[] = {
{ "if", token_type::kIF },
{ "unless", token_type::kUNLESS },
{ "while", token_type::kWHILE },
{ "until", token_type::kUNTIL },
{ "rescue", token_type::kRESCUE },
{ "defined?", token_type::kDEFINED },
{ "BEGIN", token_type::klBEGIN },
{ "END", token_type::klEND },
{ "class", token_type::kCLASS },
{ "module", token_type::kMODULE },
{ "def", token_type::kDEF },
{ "undef", token_type::kUNDEF },
{ "begin", token_type::kBEGIN },
{ "end", token_type::kEND },
{ "then", token_type::kTHEN },
{ "elsif", token_type::kELSIF },
{ "else", token_type::kELSE },
{ "ensure", token_type::kENSURE },
{ "case", token_type::kCASE },
{ "when", token_type::kWHEN },
{ "for", token_type::kFOR },
{ "break", token_type::kBREAK },
{ "next", token_type::kNEXT },
{ "redo", token_type::kREDO },
{ "retry", token_type::kRETRY },
{ "in", token_type::kIN },
{ "do", token_type::kDO },
{ "return", token_type::kRETURN },
{ "yield", token_type::kYIELD },
{ "super", token_type::kSUPER },
{ "self", token_type::kSELF },
{ "nil", token_type::kNIL },
{ "true", token_type::kTRUE },
{ "false", token_type::kFALSE },
{ "and", token_type::kAND },
{ "or", token_type::kOR },
{ "not", token_type::kNOT },
{ "alias", token_type::kALIAS },
{ "__FILE__", token_type::k__FILE__ },
{ "__LINE__", token_type::k__LINE__ },
{ "__ENCODING__", token_type::k__ENCODING__ },
{ NULL, token_type::error },
};
static size_t utf8_encode_char(int32_t uc, std::string &dst) {
if (uc < 0x00) {
return 0;
} else if (uc < 0x80) {
dst.push_back(static_cast<uint8_t>(uc));
return 1;
} else if (uc < 0x800) {
dst.push_back(static_cast<uint8_t>(0xC0 + (uc >> 6)));
dst.push_back(static_cast<uint8_t>(0x80 + (uc & 0x3F)));
return 2;
} else if (uc < 0x10000) {
dst.push_back(static_cast<uint8_t>(0xE0 + (uc >> 12)));
dst.push_back(static_cast<uint8_t>(0x80 + ((uc >> 6) & 0x3F)));
dst.push_back(static_cast<uint8_t>(0x80 + (uc & 0x3F)));
return 3;
} else if (uc < 0x110000) {
dst.push_back(static_cast<uint8_t>(0xF0 + (uc >> 18)));
dst.push_back(static_cast<uint8_t>(0x80 + ((uc >> 12) & 0x3F)));
dst.push_back(static_cast<uint8_t>(0x80 + ((uc >> 6) & 0x3F)));
dst.push_back(static_cast<uint8_t>(0x80 + (uc & 0x3F)));
return 4;
} else return 0;
}
static bool split_codepoints(const std::string &str, std::string &output) {
auto isspace = [](char c) { return c == ' ' || c == '\t'; };
const char *ptr = str.c_str();
while (*ptr) {
while (isspace(*ptr))
ptr++;
const char *start = ptr;
while (*ptr && !isspace(*ptr))
ptr++;
std::string cp {start, static_cast<size_t>(ptr - start)};
if (utf8_encode_char(std::stoi(cp, nullptr, 16), output) == 0)
return false;
}
return true;
}
static std::string gsub(const std::string&& str, const std::string&& search, const std::string&& replace) {
std::string result;
std::string::size_type from = 0;
while (true) {
auto index = str.find(search, from);
if (index == std::string::npos) {
result += str.substr(from);
break;
} else {
result += str.substr(from, index - from);
result += replace;
from = index + search.size();
}
}
return result;
}
static bool eof_codepoint(char c) {
return c == 0 || c == 0x04 || c == 0x1a;
}
token_t lexer::advance_() {
if (!token_queue.empty()) {
token_t token = token_queue.front();
token_queue.pop();
return token;
}
int cmd_state = command_start;
command_start = false;
const char* p = _p;
const char* pe = _pe;
const char* eof = _pe;
const char* tm = NULL;
const char* heredoc_e = NULL;
const char* new_herebody_s = NULL;
const char* ident_ts = NULL;
const char* ident_te = NULL;
std::string ident_tok;
%% write exec;
_p = p;
if (!token_queue.empty()) {
token_t token = token_queue.front();
token_queue.pop();
return token;
}
if (cs == lex_error) {
size_t start = (size_t)(p - source_buffer.data());
return mempool.alloc(token_type::error, start, start + 1, std::string(p - 1, 1));
}
return mempool.alloc(token_type::eof, source_buffer.size(), source_buffer.size(), "");
}
void lexer::emit(token_type type) {
emit(type, tok());
}
void lexer::emit(token_type type, const std::string& str) {
emit(type, str, ts, te);
}
void lexer::emit(token_type type, const std::string& str, const char* start, const char* end) {
size_t offset_start = (size_t)(start - source_buffer.data());
size_t offset_end = (size_t)(end - source_buffer.data());
token_queue.push(mempool.alloc(type, offset_start, offset_end, str));
}
void lexer::emit_do(bool do_block) {
if (cond.active()) {
emit(token_type::kDO_COND, "do");
} else if (cmdarg.active() || do_block) {
emit(token_type::kDO_BLOCK, "do");
} else {
emit(token_type::kDO, "do");
}
}
void lexer::emit_table(const token_table_entry* table) {
auto value = tok();
for (; table->token; ++table) {
if (value == table->token) {
emit(table->type, value);
return;
}
}
// whitequark emits a `nil` token here, but if we do `yylex` hits an assert,
// so just drop the token.
return;
}
void lexer::emit_num(const std::string& num) {
switch (num_xfrm) {
case num_xfrm_type::NONE:
emit(token_type::tINTEGER, num);
break;
case num_xfrm_type::RATIONAL:
emit(token_type::tRATIONAL, num);
break;
case num_xfrm_type::IMAGINARY:
emit(token_type::tIMAGINARY, num);
break;
case num_xfrm_type::RATIONAL_IMAGINARY:
emit(token_type::tRATIONAL_IMAGINARY, num);
break;
case num_xfrm_type::FLOAT:
emit(token_type::tFLOAT, num);
break;
case num_xfrm_type::FLOAT_IMAGINARY:
emit(token_type::tFLOAT_IMAGINARY, num);
break;
}
}
std::string lexer::convert_base(const std::string& num, int num_base) {
long int result;
if (num_base == 10) {
return num;
}
// This doesn't match Ruby's parsing but it is better than not handling it
if (!absl::numbers_internal::safe_strtoi_base(num, &result, num_base)) {
result = 0;
// dmitry: appartently we assume that outer functions reported all the errors!!!
}
return std::to_string(result);
}
diagnostic::range lexer::range(const char *start, const char *end) {
size_t token_start = (size_t)(start - source_buffer.data());
size_t token_end = (size_t)(end - source_buffer.data());
return diagnostic::range(token_start, token_end);
}
void lexer::diagnostic_(dlevel level, dclass type, const std::string &data) {
diagnostics.emplace_back(level, type, range(ts, te), data);
}
void lexer::diagnostic_(dlevel level, dclass type, diagnostic::range &&range, const std::string &data) {
diagnostics.emplace_back(level, type, range, data);
}
//
// === LITERAL STACK ===
//
template<typename... Args>
int lexer::push_literal(Args&&... args) {
literal_stack.emplace(*this, std::forward<Args>(args)...);
auto& literal = literal_stack.top();
return next_state_for_literal(literal);
}
int lexer::next_state_for_literal(literal &lit) {
if (lit.words() && lit.backslash_delimited()) {
if (lit.interpolate()) {
return lex_en_interp_backslash_delimited_words;
} else {
return lex_en_plain_backslash_delimited_words;
}
} else if (lit.words() && !lit.backslash_delimited()) {
if (lit.interpolate()) {
return lex_en_interp_words;
} else {
return lex_en_plain_words;
}
} else if (!lit.words() && lit.backslash_delimited()) {
if (lit.interpolate()) {
return lex_en_interp_backslash_delimited;
} else {
return lex_en_plain_backslash_delimited;
}
} else {
if (lit.interpolate()) {
return lex_en_interp_string;
} else {
return lex_en_plain_string;
}
}
}
literal& lexer::literal_() {
return literal_stack.top();
}
int lexer::pop_literal() {
bool was_regexp;
{
auto& old_literal = literal_stack.top();
was_regexp = old_literal.regexp();
dedentLevel_ = old_literal.dedentLevel();
}
literal_stack.pop();
if (was_regexp) {
return lex_en_regexp_modifiers;
} else {
return lex_en_expr_end;
}
}
void lexer::set_state_expr_beg() {
cs = lex_en_expr_beg;
}
void lexer::set_state_expr_end() {
cs = lex_en_expr_end;
}
void lexer::set_state_expr_endarg() {
cs = lex_en_expr_endarg;
}
void lexer::set_state_expr_fname() {
cs = lex_en_expr_fname;
}
void lexer::set_state_expr_value() {
cs = lex_en_expr_value;
}
%%{
# access @;
# getkey (@source_pts[p] || 0);
# === CHARACTER CLASSES ===
#
# Pay close attention to the differences between c_any and any.
# c_any does not include EOF and so will cause incorrect behavior
# for machine subtraction (any-except rules) and default transitions
# for scanners.
action do_nl {
// Record position of a newline for precise location reporting on tNL
// tokens.
//
// This action is embedded directly into c_nl, as it is idempotent and
// there are no cases when we need to skip it.
newline_s = p;
}
c_nl = '\n' $ do_nl;
c_space = [ \t\r\f\v];
c_space_nl = c_space | c_nl;
c_eof = 0x04 | 0x1a | 0 | zlen; # ^D, ^Z, \0, EOF
c_eol = c_nl | c_eof;
c_any = any - c_eof;
c_nl_zlen = c_nl | zlen;
c_line = any - c_nl_zlen;
c_unicode = c_any - 0x00..0x7f;
c_upper = [A-Z];
c_lower = [a-z_] | c_unicode;
c_alpha = c_lower | c_upper;
c_alnum = c_alpha | [0-9];
action do_eof {
// Sit at EOF indefinitely. #advance would return $eof each time.
// This allows to feed the lexer more data if needed; this is only used
// in tests.
//
// Note that this action is not embedded into e_eof like e_heredoc_nl and e_bs
// below. This is due to the fact that scanner state at EOF is observed
// by tests, and encapsulating it in a rule would break the introspection.
fhold; fbreak;
}
#
# === TOKEN DEFINITIONS ===
#
# All operators are punctuation. There is more to punctuation
# than just operators. Operators can be overridden by user;
# punctuation can not.
# A list of operators which are valid in the function name context, but
# have different semantics in others.
operator_fname = '[]' | '[]=' | '`' | '-@' | '+@' | '~@' | '!@' ;
# A list of operators which can occur within an assignment shortcut (+ → +=).
operator_arithmetic = '&' | '|' | '&&' | '||' | '^' | '+' | '-' |
'*' | '/' | '**' | '~' | '<<' | '>>' | '%' ;
# A list of all user-definable operators not covered by groups above.
operator_rest = '=~' | '!~' | '==' | '!=' | '!' | '===' |
'<' | '<=' | '>' | '>=' | '<=>' | '=>' ;
# Note that `{` and `}` need to be referred to as e_lbrace and e_rbrace,
# as they are ambiguous with interpolation `#{}` and should be counted.
# These braces are not present in punctuation lists.
# A list of punctuation which has different meaning when used at the
# beginning of expression.
punctuation_begin = '-' | '+' | '::' | '(' | '[' |
'*' | '**' | '&' ;
# A list of all punctuation except punctuation_begin.
punctuation_end = ',' | '=' | '->' | '(' | '[' | ']' |
'::' | '?' | ':' | '.' | '..' | '...' ;
# A list of keywords which have different meaning at the beginning of expression.
keyword_modifier = 'if' | 'unless' | 'while' | 'until' | 'rescue' ;
# A list of keywords which accept an argument-like expression, i.e. have the
# same post-processing as method calls or commands. Example: `yield 1`,
# `yield (1)`, `yield(1)`, are interpreted as if `yield` was a function.
keyword_with_arg = 'yield' | 'super' | 'not' | 'defined?' ;
# A list of keywords which accept a literal function name as an argument.
keyword_with_fname = 'def' | 'undef' | 'alias' ;
# A list of keywords which accept an expression after them.
keyword_with_value = 'else' | 'case' | 'ensure' | 'module' | 'elsif' | 'then' |
'for' | 'in' | 'do' | 'when' | 'begin' | 'class' |
'and' | 'or' ;
# A list of keywords which accept a value, and treat the keywords from
# `keyword_modifier` list as modifiers.
keyword_with_mid = 'rescue' | 'return' | 'break' | 'next' ;
# A list of keywords which do not accept an expression after them.
keyword_with_end = 'end' | 'self' | 'true' | 'false' | 'retry' |
'redo' | 'nil' | 'BEGIN' | 'END' | '__FILE__' |
'__LINE__' | '__ENCODING__';
# All keywords.
keyword = keyword_with_value | keyword_with_mid |
keyword_with_end | keyword_with_arg |
keyword_with_fname | keyword_modifier ;
constant = c_upper c_alnum*;
bareword = c_alpha c_alnum*;
call_or_var = c_lower c_alnum*;
class_var = '@@' bareword;
instance_var = '@' bareword;
global_var = '$'
( bareword | digit+
| [`'+~*$&?!@/\\;,.=:<>"] # `
| '-' c_alnum
)
;
# Ruby accepts (and fails on) variables with leading digit
# in literal context, but not in unquoted symbol body.
class_var_v = '@@' c_alnum+;
instance_var_v = '@' c_alnum+;
label = bareword [?!]? ':';
#
# === NUMERIC PARSING ===
#
int_hex = ( xdigit+ '_' )* xdigit* '_'? ;
int_dec = ( digit+ '_' )* digit* '_'? ;
int_bin = ( [01]+ '_' )* [01]* '_'? ;
flo_int = [1-9] [0-9]* ( '_' digit+ )* | '0';
flo_frac = '.' ( digit+ '_' )* digit+;
flo_pow = [eE] [+\-]? ( digit+ '_' )* digit+;
int_suffix =
'' % { num_xfrm = num_xfrm_type::NONE; }
| 'r' % { num_xfrm = num_xfrm_type::RATIONAL; }
| 'i' % { num_xfrm = num_xfrm_type::IMAGINARY; }
| 'ri' % { num_xfrm = num_xfrm_type::RATIONAL_IMAGINARY; };
flo_pow_suffix =
'' % { num_xfrm = num_xfrm_type::FLOAT; }
| 'i' % { num_xfrm = num_xfrm_type::FLOAT_IMAGINARY; };
flo_suffix =
flo_pow_suffix
| 'r' % { num_xfrm = num_xfrm_type::RATIONAL; }
| 'ri' % { num_xfrm = num_xfrm_type::RATIONAL_IMAGINARY; };
#
# === ESCAPE SEQUENCE PARSING ===
#
# Escape parsing code is a Ragel pattern, not a scanner, and therefore
# it shouldn't directly raise errors or perform other actions with side effects.
# In reality this would probably just mess up error reporting in pathological
# cases, through.
# The amount of code required to parse \M\C stuff correctly is ridiculous.
escaped_nl = "\\" c_nl;
action unicode_points {
auto codepoint_str = tok(escape_s + 2, p - 1);
std::string result;
if (split_codepoints(codepoint_str, result)) {
escape = std::make_unique<std::string>(result);
} else {
auto codepoint_s = escape_s + 2;
diagnostic_(dlevel::ERROR, dclass::UnicodePointTooLarge,
range(codepoint_s, codepoint_s + codepoint_str.size()));
}
}
action unescape_char {
char esc = unescape(p[-1]);
if (esc) {
escape = std::make_unique<std::string>(&esc, 1);
} else {
escape = std::make_unique<std::string>(p - 1, 1);
}
}
action invalid_complex_escape {
diagnostic_(dlevel::FATAL, dclass::InvalidEscape);
}
action slash_c_char {
// TODO multibyte
char c = escape->at(0) & 0x9f;
escape = std::make_unique<std::string>(&c, 1);
}
action slash_m_char {
// TODO multibyte
char c = escape->at(0) | 0x80;
escape = std::make_unique<std::string>(&c, 1);
}
maybe_escaped_char = (
'\\' c_any %unescape_char
| ( c_any - [\\] ) % { escape = std::make_unique<std::string>(p - 1, 1); /* TODO multibyte */ }
);
maybe_escaped_ctrl_char = ( # why?!
'\\' c_any %unescape_char %slash_c_char
| '?' % { escape = std::make_unique<std::string>("\x7f"); }
| ( c_any - [\\?] ) % { escape = std::make_unique<std::string>(p - 1, 1); /* TODO multibyte */ } %slash_c_char
);
escape = (
# \377
[0-7]{1,3}
% {
auto esc = tok(escape_s, p);
char c = std::stoi(esc, nullptr, 8);
escape = std::make_unique<std::string>(&c, 1);
}
# \xff
| 'x' xdigit{1,2}
% {
auto esc = tok(escape_s + 1, p);
char c = std::stoi(esc, nullptr, 16);
escape = std::make_unique<std::string>(&c, 1);
}
# \u263a
| 'u' xdigit{4}
% {
std::string result;
split_codepoints(tok(escape_s + 1, p), result);
escape = std::make_unique<std::string>(result);
}
# %q[\x]
| 'x' ( c_any - xdigit )
% {
diagnostic_(dlevel::FATAL, dclass::InvalidHexEscape, range(escape_s - 1, p + 2));
}
# %q[\u123] %q[\u{12]
| 'u' ( c_any{0,4} -
xdigit{4} - # \u1234 is valid
( '{' xdigit{1,3} # \u{1 \u{12 \u{123 are valid
| '{' xdigit [ \t}] any? # \u{1. \u{1} are valid
| '{' xdigit{2} [ \t}] # \u{12. \u{12} are valid
)
)
% {
diagnostic_(dlevel::FATAL, dclass::InvalidUnicodeEscape, range(escape_s - 1, p));
}
# \u{123 456}
| 'u{' ( xdigit{1,6} [ \t] )*
( xdigit{1,6} '}'
%unicode_points
| ( xdigit* ( c_any - xdigit - '}' )+ '}'
| ( c_any - '}' )* c_eof
| xdigit{7,}
) % {
diagnostic_(dlevel::FATAL, dclass::UnterminatedUnicode, range(p - 1, p));
}
)
# \C-\a \cx
| ( 'C-' | 'c' ) escaped_nl?
maybe_escaped_ctrl_char
# \M-a
| 'M-' escaped_nl?
maybe_escaped_char
%slash_m_char
# \C-\M-f \M-\cf \c\M-f
| ( ( 'C-' | 'c' ) escaped_nl? '\\M-'
| 'M-\\' escaped_nl? ( 'C-' | 'c' ) ) escaped_nl?
maybe_escaped_ctrl_char
%slash_m_char
| 'C' c_any %invalid_complex_escape
| 'M' c_any %invalid_complex_escape
| ( 'M-\\C' | 'C-\\M' ) c_any %invalid_complex_escape
| ( c_any - [0-7xuCMc] ) %unescape_char
| c_eof % {
diagnostic_(dlevel::FATAL, dclass::EscapeEof, range(p - 1, p));
}
);
# Use rules in form of `e_bs escape' when you need to parse a sequence.
e_bs = '\\' % {
escape_s = p;
escape = nullptr;
};
#
# === STRING AND HEREDOC PARSING ===
#
# Heredoc parsing is quite a complex topic. First, consider that heredocs
# can be arbitrarily nested. For example:
#
# puts <<CODE
# the result is: #{<<RESULT.inspect
# i am a heredoc
# RESULT
# }
# CODE
#
# which, incidentally, evaluates to:
#
# the result is: " i am a heredoc\n"
#
# To parse them, lexer refers to two kinds (remember, nested heredocs)
# of positions in the input stream, namely heredoc_e
# (HEREDOC declaration End) and @herebody_s (HEREdoc BODY line Start).
#
# heredoc_e is simply contained inside the corresponding Literal, and
# when the heredoc is closed, the lexing is restarted from that position.
#
# @herebody_s is quite more complex. First, @herebody_s changes after each
# heredoc line is lexed. This way, at '\n' tok(@herebody_s, @te) always
# contains the current line, and also when a heredoc is started, @herebody_s
# contains the position from which the heredoc will be lexed.
#
# Second, as (insanity) there are nested heredocs, we need to maintain a
# stack of these positions. Each time #push_literal is called, it saves current
# @heredoc_s to literal.saved_herebody_s, and after an interpolation (possibly
# containing another heredocs) is closed, the previous value is restored.
e_heredoc_nl = c_nl % {
// After every heredoc was parsed, herebody_s contains the
// position of next token after all heredocs.
if (herebody_s) {
p = herebody_s;
herebody_s = NULL;
}
};
action extend_string {
auto str = tok();
std::string lookahead;