forked from fish-shell/fish-shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse_tree.cpp
1553 lines (1343 loc) · 54.2 KB
/
parse_tree.cpp
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
#include "parse_productions.h"
#include "tokenizer.h"
#include "fallback.h"
#include "wutil.h"
#include "proc.h"
#include <vector>
#include <algorithm>
using namespace parse_productions;
static bool production_is_empty(const production_t *production)
{
return (*production)[0] == token_type_invalid;
}
void swap2(parse_node_tree_t &a, parse_node_tree_t &b)
{
fprintf(stderr, "Swapping!\n");
// This uses the base vector implementation
a.swap(b);
}
/** Returns a string description of this parse error */
wcstring parse_error_t::describe_with_prefix(const wcstring &src, const wcstring &prefix, bool is_interactive, bool skip_caret) const
{
wcstring result = text;
if (! skip_caret && source_start < src.size() && source_start + source_length <= src.size())
{
// Locate the beginning of this line of source
size_t line_start = 0;
// Look for a newline prior to source_start. If we don't find one, start at the beginning of the string; otherwise start one past the newline. Note that source_start may itself point at a newline; we want to find the newline before it.
if (source_start > 0)
{
size_t newline = src.find_last_of(L'\n', source_start - 1);
if (newline != wcstring::npos)
{
line_start = newline + 1;
}
}
// Look for the newline after the source range. If the source range itself includes a newline, that's the one we want, so start just before the end of the range
size_t last_char_in_range = (source_length == 0 ? source_start : source_start + source_length - 1);
size_t line_end = src.find(L'\n', last_char_in_range);
if (line_end == wcstring::npos)
{
line_end = src.size();
}
assert(line_end >= line_start);
assert(source_start >= line_start);
// Don't include the caret and line if we're interactive this is the first line, because then it's obvious
bool skip_caret = (is_interactive && source_start == 0);
if (! skip_caret)
{
// Append the line of text.
if (! result.empty())
{
result.push_back(L'\n');
}
result.append(prefix);
result.append(src, line_start, line_end - line_start);
// Append the caret line. The input source may include tabs; for that reason we construct a "caret line" that has tabs in corresponding positions
const wcstring line_to_measure = prefix + wcstring(src, line_start, source_start - line_start);
wcstring caret_space_line;
caret_space_line.reserve(source_start - line_start);
for (size_t i=0; i < line_to_measure.size(); i++)
{
wchar_t wc = line_to_measure.at(i);
if (wc == L'\t')
{
caret_space_line.push_back(L'\t');
}
else if (wc == L'\n')
{
/* It's possible that the source_start points at a newline itself. In that case, pretend it's a space. We only expect this to be at the end of the string. */
caret_space_line.push_back(L' ');
}
else
{
int width = fish_wcwidth(wc);
if (width > 0)
{
caret_space_line.append(static_cast<size_t>(width), L' ');
}
}
}
result.push_back(L'\n');
result.append(caret_space_line);
result.push_back(L'^');
}
}
return result;
}
wcstring parse_error_t::describe(const wcstring &src) const
{
return this->describe_with_prefix(src, wcstring(), get_is_interactive(), false);
}
wcstring parse_errors_description(const parse_error_list_t &errors, const wcstring &src, const wchar_t *prefix)
{
wcstring target;
for (size_t i=0; i < errors.size(); i++)
{
if (i > 0)
{
target.push_back(L'\n');
}
if (prefix != NULL)
{
target.append(prefix);
target.append(L": ");
}
target.append(errors.at(i).describe(src));
}
return target;
}
void parse_error_offset_source_start(parse_error_list_t *errors, size_t amt)
{
assert(errors != NULL);
if (amt > 0)
{
size_t i, max = errors->size();
for (i=0; i < max; i++)
{
parse_error_t *error = &errors->at(i);
/* preserve the special meaning of -1 as 'unknown' */
if (error->source_start != SOURCE_LOCATION_UNKNOWN)
{
error->source_start += amt;
}
}
}
}
/** Returns a string description of the given token type */
wcstring token_type_description(parse_token_type_t type)
{
switch (type)
{
case token_type_invalid:
return L"invalid";
case symbol_job_list:
return L"job_list";
case symbol_job:
return L"job";
case symbol_job_continuation:
return L"job_continuation";
case symbol_statement:
return L"statement";
case symbol_block_statement:
return L"block_statement";
case symbol_block_header:
return L"block_header";
case symbol_for_header:
return L"for_header";
case symbol_while_header:
return L"while_header";
case symbol_begin_header:
return L"begin_header";
case symbol_function_header:
return L"function_header";
case symbol_if_statement:
return L"if_statement";
case symbol_if_clause:
return L"if_clause";
case symbol_else_clause:
return L"else_clause";
case symbol_else_continuation:
return L"else_continuation";
case symbol_switch_statement:
return L"switch_statement";
case symbol_case_item_list:
return L"case_item_list";
case symbol_case_item:
return L"case_item";
case symbol_argument_list:
return L"argument_list";
case symbol_freestanding_argument_list:
return L"freestanding_argument_list";
case symbol_boolean_statement:
return L"boolean_statement";
case symbol_decorated_statement:
return L"decorated_statement";
case symbol_plain_statement:
return L"plain_statement";
case symbol_arguments_or_redirections_list:
return L"arguments_or_redirections_list";
case symbol_argument_or_redirection:
return L"argument_or_redirection";
case symbol_argument:
return L"symbol_argument";
case symbol_redirection:
return L"symbol_redirection";
case symbol_optional_background:
return L"optional_background";
case symbol_end_command:
return L"symbol_end_command";
case parse_token_type_string:
return L"token_string";
case parse_token_type_pipe:
return L"token_pipe";
case parse_token_type_redirection:
return L"token_redirection";
case parse_token_type_background:
return L"token_background";
case parse_token_type_end:
return L"token_end";
case parse_token_type_terminate:
return L"token_terminate";
case parse_special_type_parse_error:
return L"parse_error";
case parse_special_type_tokenizer_error:
return L"tokenizer_error";
case parse_special_type_comment:
return L"comment";
}
return format_string(L"Unknown token type %ld", static_cast<long>(type));
}
#define LONGIFY(x) L ## x
#define KEYWORD_MAP(x) { parse_keyword_ ## x , LONGIFY(#x) }
static const struct
{
const parse_keyword_t keyword;
const wchar_t * const name;
}
keyword_map[] =
{
KEYWORD_MAP(none),
KEYWORD_MAP(if),
KEYWORD_MAP(else),
KEYWORD_MAP(for),
KEYWORD_MAP(in),
KEYWORD_MAP(while),
KEYWORD_MAP(begin),
KEYWORD_MAP(function),
KEYWORD_MAP(switch),
KEYWORD_MAP(case),
KEYWORD_MAP(end),
KEYWORD_MAP(and),
KEYWORD_MAP(or),
KEYWORD_MAP(not),
KEYWORD_MAP(command),
KEYWORD_MAP(builtin),
KEYWORD_MAP(exec)
};
wcstring keyword_description(parse_keyword_t k)
{
if (k >= 0 && k <= LAST_KEYWORD)
{
return keyword_map[k].name;
}
else
{
return format_string(L"Unknown keyword type %ld", static_cast<long>(k));
}
}
static wcstring token_type_user_presentable_description(parse_token_type_t type, parse_keyword_t keyword = parse_keyword_none)
{
if (keyword != parse_keyword_none)
{
return format_string(L"keyword '%ls'", keyword_description(keyword).c_str());
}
switch (type)
{
/* Hackish. We only support the following types. */
case symbol_statement:
return L"a command";
case symbol_argument:
return L"an argument";
case parse_token_type_string:
return L"a string";
case parse_token_type_pipe:
return L"a pipe";
case parse_token_type_redirection:
return L"a redirection";
case parse_token_type_background:
return L"a '&'";
case parse_token_type_end:
return L"end of the statement";
default:
return format_string(L"a %ls", token_type_description(type).c_str());
}
}
/** Returns a string description of the given parse node */
wcstring parse_node_t::describe(void) const
{
wcstring result = token_type_description(type);
append_format(result, L" (prod %d)", this->production_idx);
return result;
}
/** Returns a string description of the given parse token */
wcstring parse_token_t::describe() const
{
wcstring result = token_type_description(type);
if (keyword != parse_keyword_none)
{
append_format(result, L" <%ls>", keyword_description(keyword).c_str());
}
return result;
}
/** A string description appropriate for presentation to the user */
wcstring parse_token_t::user_presentable_description() const
{
return token_type_user_presentable_description(type, keyword);
}
/* Convert from tokenizer_t's token type to a parse_token_t type */
static inline parse_token_type_t parse_token_type_from_tokenizer_token(enum token_type tokenizer_token_type)
{
parse_token_type_t result = token_type_invalid;
switch (tokenizer_token_type)
{
case TOK_STRING:
result = parse_token_type_string;
break;
case TOK_PIPE:
result = parse_token_type_pipe;
break;
case TOK_END:
result = parse_token_type_end;
break;
case TOK_BACKGROUND:
result = parse_token_type_background;
break;
case TOK_REDIRECT_OUT:
case TOK_REDIRECT_APPEND:
case TOK_REDIRECT_IN:
case TOK_REDIRECT_FD:
case TOK_REDIRECT_NOCLOB:
result = parse_token_type_redirection;
break;
case TOK_ERROR:
result = parse_special_type_tokenizer_error;
break;
case TOK_COMMENT:
result = parse_special_type_comment;
break;
default:
fprintf(stderr, "Bad token type %d passed to %s\n", (int)tokenizer_token_type, __FUNCTION__);
assert(0);
break;
}
return result;
}
/* Helper function for dump_tree */
static void dump_tree_recursive(const parse_node_tree_t &nodes, const wcstring &src, node_offset_t node_idx, size_t indent, wcstring *result, size_t *line, node_offset_t *inout_first_node_not_dumped)
{
assert(node_idx < nodes.size());
// Update first_node_not_dumped
// This takes a bit of explanation. While it's true that a parse tree may be a "forest", its individual trees are "compact," meaning they are not interleaved. Thus we keep track of the largest node index as we descend a tree. One past the largest is the start of the next tree.
if (*inout_first_node_not_dumped <= node_idx)
{
*inout_first_node_not_dumped = node_idx + 1;
}
const parse_node_t &node = nodes.at(node_idx);
const size_t spacesPerIndent = 2;
// unindent statement lists by 1 to flatten them
if (node.type == symbol_job_list || node.type == symbol_arguments_or_redirections_list)
{
if (indent > 0) indent -= 1;
}
append_format(*result, L"%2lu - %l2u ", *line, node_idx);
result->append(indent * spacesPerIndent, L' ');;
result->append(node.describe());
if (node.child_count > 0)
{
append_format(*result, L" <%lu children>", node.child_count);
}
if (node.has_source() && node.type == parse_token_type_string)
{
result->append(L": \"");
result->append(src, node.source_start, node.source_length);
result->append(L"\"");
}
if (node.type != parse_token_type_string)
{
if (node.has_source())
{
append_format(*result, L" [%ld, %ld]", (long)node.source_start, (long)node.source_length);
}
else
{
append_format(*result, L" [no src]", (long)node.source_start, (long)node.source_length);
}
}
result->push_back(L'\n');
++*line;
for (node_offset_t child_idx = node.child_start; child_idx < node.child_start + node.child_count; child_idx++)
{
dump_tree_recursive(nodes, src, child_idx, indent + 1, result, line, inout_first_node_not_dumped);
}
}
/* Gives a debugging textual description of a parse tree. Note that this supports "parse forests" too. That is, our tree may not really be a tree, but instead a collection of trees. */
wcstring parse_dump_tree(const parse_node_tree_t &nodes, const wcstring &src)
{
if (nodes.empty())
return L"(empty!)";
node_offset_t first_node_not_dumped = 0;
size_t line = 0;
wcstring result;
while (first_node_not_dumped < nodes.size())
{
if (first_node_not_dumped > 0)
{
result.append(L"---New Tree---\n");
}
dump_tree_recursive(nodes, src, first_node_not_dumped, 0, &result, &line, &first_node_not_dumped);
}
return result;
}
/* Struct representing elements of the symbol stack, used in the internal state of the LL parser */
struct parse_stack_element_t
{
enum parse_token_type_t type;
enum parse_keyword_t keyword;
node_offset_t node_idx;
explicit parse_stack_element_t(parse_token_type_t t, node_offset_t idx) : type(t), keyword(parse_keyword_none), node_idx(idx)
{
}
explicit parse_stack_element_t(production_element_t e, node_offset_t idx) : type(production_element_type(e)), keyword(production_element_keyword(e)), node_idx(idx)
{
}
wcstring describe(void) const
{
wcstring result = token_type_description(type);
if (keyword != parse_keyword_none)
{
append_format(result, L" <%ls>", keyword_description(keyword).c_str());
}
return result;
}
/* Returns a name that we can show to the user, e.g. "a command" */
wcstring user_presentable_description(void) const
{
return token_type_user_presentable_description(type, keyword);
}
};
/* The parser itself, private implementation of class parse_t. This is a hand-coded table-driven LL parser. Most hand-coded LL parsers are recursive descent, but recursive descent parsers are difficult to "pause", unlike table-driven parsers. */
class parse_ll_t
{
/* Traditional symbol stack of the LL parser */
std::vector<parse_stack_element_t> symbol_stack;
/* Parser output. This is a parse tree, but stored in an array. */
parse_node_tree_t nodes;
/* Whether we ran into a fatal error, including parse errors or tokenizer errors */
bool fatal_errored;
/* Whether we should collect error messages or not */
bool should_generate_error_messages;
/* List of errors we have encountered */
parse_error_list_t errors;
/* The symbol stack can contain terminal types or symbols. Symbols go on to do productions, but terminal types are just matched against input tokens. */
bool top_node_handle_terminal_types(parse_token_t token);
void parse_error(const wchar_t *expected, parse_token_t token);
void parse_error(parse_token_t token, parse_error_code_t code, const wchar_t *format, ...);
void parse_error_failed_production(struct parse_stack_element_t &elem, parse_token_t token);
void parse_error_unbalancing_token(parse_token_t token);
void dump_stack(void) const;
// Get the node corresponding to the top element of the stack
parse_node_t &node_for_top_symbol()
{
PARSE_ASSERT(! symbol_stack.empty());
const parse_stack_element_t &top_symbol = symbol_stack.back();
PARSE_ASSERT(top_symbol.node_idx != NODE_OFFSET_INVALID);
PARSE_ASSERT(top_symbol.node_idx < nodes.size());
return nodes.at(top_symbol.node_idx);
}
parse_token_type_t stack_top_type() const
{
return symbol_stack.back().type;
}
// Pop from the top of the symbol stack, then push the given production, updating node counts. Note that production_t has type "pointer to array" so some care is required.
inline void symbol_stack_pop_push_production(const production_t *production)
{
bool logit = false;
if (logit)
{
size_t count = 0;
fprintf(stderr, "Applying production:\n");
for (size_t i=0; i < MAX_SYMBOLS_PER_PRODUCTION; i++)
{
production_element_t elem = (*production)[i];
if (production_element_is_valid(elem))
{
parse_token_type_t type = production_element_type(elem);
parse_keyword_t keyword = production_element_keyword(elem);
fprintf(stderr, "\t%ls <%ls>\n", token_type_description(type).c_str(), keyword_description(keyword).c_str());
count++;
}
}
if (! count) fprintf(stderr, "\t<empty>\n");
}
// Get the parent index. But we can't get the parent parse node yet, since it may be made invalid by adding children
const node_offset_t parent_node_idx = symbol_stack.back().node_idx;
// Add the children. Confusingly, we want our nodes to be in forwards order (last token last, so dumps look nice), but the symbols should be reverse order (last token first, so it's lowest on the stack)
const size_t child_start_big = nodes.size();
assert(child_start_big < NODE_OFFSET_INVALID);
node_offset_t child_start = static_cast<node_offset_t>(child_start_big);
// To avoid constructing multiple nodes, we push_back a single one that we modify
parse_node_t representative_child(token_type_invalid);
representative_child.parent = parent_node_idx;
node_offset_t child_count = 0;
for (size_t i=0; i < MAX_SYMBOLS_PER_PRODUCTION; i++)
{
production_element_t elem = (*production)[i];
if (! production_element_is_valid(elem))
{
// All done, bail out
break;
}
// Append the parse node.
representative_child.type = production_element_type(elem);
nodes.push_back(representative_child);
child_count++;
}
// Update the parent
parse_node_t &parent_node = nodes.at(parent_node_idx);
// Should have no children yet
PARSE_ASSERT(parent_node.child_count == 0);
// Tell the node about its children
parent_node.child_start = child_start;
parent_node.child_count = child_count;
// Replace the top of the stack with new stack elements corresponding to our new nodes. Note that these go in reverse order.
symbol_stack.pop_back();
symbol_stack.reserve(symbol_stack.size() + child_count);
node_offset_t idx = child_count;
while (idx--)
{
production_element_t elem = (*production)[idx];
PARSE_ASSERT(production_element_is_valid(elem));
symbol_stack.push_back(parse_stack_element_t(elem, child_start + idx));
}
}
public:
/* Constructor */
parse_ll_t(enum parse_token_type_t goal) : fatal_errored(false), should_generate_error_messages(true)
{
this->symbol_stack.reserve(16);
this->nodes.reserve(64);
this->reset_symbols_and_nodes(goal);
}
/* Input */
void accept_tokens(parse_token_t token1, parse_token_t token2);
/* Report tokenizer errors */
void report_tokenizer_error(parse_token_t token, int tok_err, const wchar_t *tok_error);
/* Indicate if we hit a fatal error */
bool has_fatal_error(void) const
{
return this->fatal_errored;
}
/* Indicate whether we want to generate error messages */
void set_should_generate_error_messages(bool flag)
{
this->should_generate_error_messages = flag;
}
/* Clear the parse symbol stack (but not the node tree). Add a node of the given type as the goal node. This is called from the constructor */
void reset_symbols(enum parse_token_type_t goal);
/* Clear the parse symbol stack and the node tree. Add a node of the given type as the goal node. This is called from the constructor. */
void reset_symbols_and_nodes(enum parse_token_type_t goal);
/* Once parsing is complete, determine the ranges of intermediate nodes */
void determine_node_ranges();
/* Acquire output after parsing. This transfers directly from within self */
void acquire_output(parse_node_tree_t *output, parse_error_list_t *errors);
};
void parse_ll_t::dump_stack(void) const
{
// Walk backwards from the top, looking for parents
wcstring_list_t lines;
if (symbol_stack.empty())
{
lines.push_back(L"(empty)");
}
else
{
node_offset_t child = symbol_stack.back().node_idx;
node_offset_t cursor = child;
lines.push_back(nodes.at(cursor).describe());
while (cursor--)
{
const parse_node_t &node = nodes.at(cursor);
if (node.child_start <= child && node.child_start + node.child_count > child)
{
lines.push_back(node.describe());
child = cursor;
}
}
}
fprintf(stderr, "Stack dump (%lu elements):\n", symbol_stack.size());
for (size_t idx = 0; idx < lines.size(); idx++)
{
fprintf(stderr, " %ls\n", lines.at(idx).c_str());
}
}
// Give each node a source range equal to the union of the ranges of its children
// Terminal nodes already have source ranges (and no children)
// Since children always appear after their parents, we can implement this very simply by walking backwards
void parse_ll_t::determine_node_ranges(void)
{
size_t idx = nodes.size();
while (idx--)
{
parse_node_t *parent = &nodes[idx];
// Skip nodes that already have a source range. These are terminal nodes.
if (parent->source_start != SOURCE_OFFSET_INVALID)
continue;
// Ok, this node needs a source range. Get all of its children, and then set its range.
source_offset_t min_start = SOURCE_OFFSET_INVALID, max_end = 0; //note SOURCE_OFFSET_INVALID is huge
for (node_offset_t i=0; i < parent->child_count; i++)
{
const parse_node_t &child = nodes.at(parent->child_offset(i));
if (child.has_source())
{
min_start = std::min(min_start, child.source_start);
max_end = std::max(max_end, child.source_start + child.source_length);
}
}
if (min_start != SOURCE_OFFSET_INVALID)
{
assert(max_end >= min_start);
parent->source_start = min_start;
parent->source_length = max_end - min_start;
}
}
}
void parse_ll_t::acquire_output(parse_node_tree_t *output, parse_error_list_t *errors)
{
if (output != NULL)
{
output->swap(this->nodes);
}
this->nodes.clear();
if (errors != NULL)
{
errors->swap(this->errors);
}
this->errors.clear();
this->symbol_stack.clear();
}
void parse_ll_t::parse_error(parse_token_t token, parse_error_code_t code, const wchar_t *fmt, ...)
{
this->fatal_errored = true;
if (this->should_generate_error_messages)
{
//this->dump_stack();
parse_error_t err;
va_list va;
va_start(va, fmt);
err.text = vformat_string(fmt, va);
err.code = code;
va_end(va);
err.source_start = token.source_start;
err.source_length = token.source_length;
this->errors.push_back(err);
}
}
// Unbalancing token. This includes 'else' or 'case' or 'end' outside of the appropriate block
// This essentially duplicates some logic from resolving the production for symbol_statement_list - yuck
void parse_ll_t::parse_error_unbalancing_token(parse_token_t token)
{
this->fatal_errored = true;
if (this->should_generate_error_messages)
{
switch (token.keyword)
{
case parse_keyword_end:
this->parse_error(token, parse_error_unbalancing_end, L"'end' outside of a block");
break;
case parse_keyword_else:
this->parse_error(token, parse_error_unbalancing_else, L"'else' builtin not inside of if block");
break;
case parse_keyword_case:
this->parse_error(token, parse_error_unbalancing_case, L"'case' builtin not inside of switch block");
break;
default:
// At the moment, this case should only be hit if you parse a freestanding_argument_list
// For example, 'complete -c foo -a 'one & three'
// Hackish error message for that case
if (! symbol_stack.empty() && symbol_stack.back().type == symbol_freestanding_argument_list)
{
this->parse_error(token, parse_error_generic, L"Expected %ls, but found %ls", token_type_user_presentable_description(symbol_argument).c_str(), token.user_presentable_description().c_str());
}
else
{
this->parse_error(token, parse_error_generic, L"Did not expect %ls", token.user_presentable_description().c_str());
}
break;
}
}
}
// This is a 'generic' parse error when we can't match the top of the stack element
void parse_ll_t::parse_error_failed_production(struct parse_stack_element_t &stack_elem, parse_token_t token)
{
fatal_errored = true;
if (this->should_generate_error_messages)
{
bool done = false;
/* Check for || */
if (token.type == parse_token_type_pipe && token.source_start > 0)
{
/* Here we wanted a statement and instead got a pipe. See if this is a double pipe: foo || bar. If so, we have a special error message. */
const parse_node_t *prev_pipe = nodes.find_node_matching_source_location(parse_token_type_pipe, token.source_start - 1, NULL);
if (prev_pipe != NULL)
{
/* The pipe of the previous job abuts our current token. So we have ||. */
this->parse_error(token, parse_error_double_pipe, CMD_OR_ERR_MSG);
done = true;
}
}
/* Check for && */
if (! done && token.type == parse_token_type_background && token.source_start > 0)
{
/* Check to see if there was a previous token_background */
const parse_node_t *prev_background = nodes.find_node_matching_source_location(parse_token_type_background, token.source_start - 1, NULL);
if (prev_background != NULL)
{
/* We have &&. */
this->parse_error(token, parse_error_double_background, CMD_AND_ERR_MSG);
done = true;
}
}
if (! done)
{
const wcstring expected = stack_elem.user_presentable_description();
this->parse_error(expected.c_str(), token);
}
}
}
void parse_ll_t::report_tokenizer_error(parse_token_t token, int tok_err_code, const wchar_t *tok_error)
{
assert(tok_error != NULL);
parse_error_code_t parse_error_code;
switch (tok_err_code)
{
case TOK_UNTERMINATED_QUOTE:
parse_error_code = parse_error_tokenizer_unterminated_quote;
break;
case TOK_UNTERMINATED_SUBSHELL:
parse_error_code = parse_error_tokenizer_unterminated_subshell;
break;
case TOK_UNTERMINATED_ESCAPE:
parse_error_code = parse_error_tokenizer_unterminated_escape;
break;
case TOK_OTHER:
default:
parse_error_code = parse_error_tokenizer_other;
break;
}
this->parse_error(token, parse_error_code, L"%ls", tok_error);
}
void parse_ll_t::parse_error(const wchar_t *expected, parse_token_t token)
{
fatal_errored = true;
if (this->should_generate_error_messages)
{
this->parse_error(token, parse_error_generic, L"Expected %ls, but instead found %ls", expected, token.user_presentable_description().c_str());
}
}
void parse_ll_t::reset_symbols(enum parse_token_type_t goal)
{
/* Add a new goal node, and then reset our symbol list to point at it */
node_offset_t where = static_cast<node_offset_t>(nodes.size());
nodes.push_back(parse_node_t(goal));
symbol_stack.clear();
symbol_stack.push_back(parse_stack_element_t(goal, where)); // goal token
this->fatal_errored = false;
}
/* Reset both symbols and nodes */
void parse_ll_t::reset_symbols_and_nodes(enum parse_token_type_t goal)
{
nodes.clear();
this->reset_symbols(goal);
}
static bool type_is_terminal_type(parse_token_type_t type)
{
switch (type)
{
case parse_token_type_string:
case parse_token_type_pipe:
case parse_token_type_redirection:
case parse_token_type_background:
case parse_token_type_end:
case parse_token_type_terminate:
return true;
default:
return false;
}
}
bool parse_ll_t::top_node_handle_terminal_types(parse_token_t token)
{
PARSE_ASSERT(! symbol_stack.empty());
PARSE_ASSERT(token.type >= FIRST_PARSE_TOKEN_TYPE);
bool handled = false;
parse_stack_element_t &stack_top = symbol_stack.back();
if (type_is_terminal_type(stack_top.type))
{
// The top of the stack is terminal. We are going to handle this (because we can't produce from a terminal type)
handled = true;
// Now see if we actually matched
bool matched = false;
if (stack_top.type == token.type)
{
switch (stack_top.type)
{
case parse_token_type_string:
// We matched if the keywords match, or no keyword was required
matched = (stack_top.keyword == parse_keyword_none || stack_top.keyword == token.keyword);
break;
default:
// For other types, we only require that the types match
matched = true;
break;
}
}
if (matched)
{
// Success. Tell the node that it matched this token, and what its source range is
// In the parse phase, we only set source ranges for terminal types. We propagate ranges to parent nodes afterwards.
parse_node_t &node = node_for_top_symbol();
node.source_start = token.source_start;
node.source_length = token.source_length;
}
else
{
// Failure
if (stack_top.type == parse_token_type_string && token.type == parse_token_type_string)
{
// Keyword failure. We should unify this with the 'matched' computation above.
assert(stack_top.keyword != parse_keyword_none && stack_top.keyword != token.keyword);
// Check to see which keyword we got which was considered wrong
switch (token.keyword)
{
// Some keywords are only valid in certain contexts. If this cascaded all the way down through the outermost job_list, it was not in a valid context.
case parse_keyword_case:
case parse_keyword_end:
case parse_keyword_else:
this->parse_error_unbalancing_token(token);
break;
case parse_keyword_none:
{
// This is a random other string (not a keyword)
const wcstring expected = keyword_description(stack_top.keyword);
this->parse_error(token, parse_error_generic, L"Expected keyword '%ls'", expected.c_str());
break;
}
default:
{
// Got a real keyword we can report
const wcstring actual = (token.keyword == parse_keyword_none ? token.describe() : keyword_description(token.keyword));
const wcstring expected = keyword_description(stack_top.keyword);
this->parse_error(token, parse_error_generic, L"Expected keyword '%ls', instead got keyword '%ls'", expected.c_str(), actual.c_str());
break;
}
}
}
else
{
const wcstring expected = stack_top.user_presentable_description();
this->parse_error(expected.c_str(), token);
}
}
// We handled the token, so pop the symbol stack
symbol_stack.pop_back();
}
return handled;
}
void parse_ll_t::accept_tokens(parse_token_t token1, parse_token_t token2)
{
bool logit = false;
if (logit)
{
fprintf(stderr, "Accept token %ls\n", token1.describe().c_str());
}
PARSE_ASSERT(token1.type >= FIRST_PARSE_TOKEN_TYPE);
bool consumed = false;