Debian Codegraph @

vendor/wikimedia/shellbox/src/ShellParser/shell.pegphp

raw
1 /*
2 * Recognise a shell command per the POSIX Shell Command Language specification
3 * and return an AST.
4 *
5 * Tree construction may be overridden in a subclass by overriding the node()
6 * function.
7 *
8 * In general, AST nodes have a name and a contents array. For a binary
9 * operator, the first element of the contents array will be the left
10 * operand, and the second element will be the right operand. In more complex
11 * cases, operands should generally be named by enclosing them within a named
12 * node.
13 *
14 * Each element of the contents array may either be a string, a node, or an
15 * array of nodes.
16 */
17
18 /*
19 * File initializer
20 */
21 {
22 use Wikimedia\WikiPEG\InternalError;
23 // @phan-file-suppress PhanUnusedGotoLabel
24 // @phan-file-suppress PhanNoopSwitchCases
25 }
26
27 /*
28 * Class initializer
29 */
30 {
31 /**
32 * Overridable tree node constructor
33 *
34 * @stable to override
35 * @param string $type
36 * @param array|Node|string $contents
37 * @return Node
38 */
39 protected function node( $type, $contents ) {
40 return new Node( $type, $contents );
41 }
42
43 /**
44 * Combine arrays and non-array items into a single flat array.
45 *
46 * @param array|Node|string|null ...$items
47 * @return array
48 * @phan-return array<Node|string>
49 */
50 private function merge( ...$items ) {
51 if ( !$items ) {
52 return [];
53 }
54 $mergeArgs = [];
55 foreach ( $items as $item ) {
56 if ( $item !== null ) {
57 if ( !is_array( $item ) ) {
58 $mergeArgs[] = [ $item ];
59 } else {
60 $mergeArgs[] = $item;
61 }
62 }
63 }
64 return array_merge( ...$mergeArgs );
65 }
66 }
67
68 program =
69 linebreak commands:complete_commands linebreak
70 {
71 return $this->node( 'program', $commands );
72 }
73 / linebreak
74 {
75 return $this->node( 'program', [] );
76 }
77
78 complete_commands =
79 (
80 c:complete_command newline_list
81 {
82 return $c;
83 }
84 / complete_command
85 )*
86
87 complete_command =
88 OWS
89 list: (
90 nodes: (
91 item: and_or
92 separator: $separator_op
93 {
94 if ( $separator && $separator[0] === '&' ) {
95 return $this->node( 'background', $item );
96 } else {
97 return $item;
98 }
99 }
100 )+
101 last: and_or?
102 {
103 if ( $last ) {
104 $nodes[] = $last;
105 }
106 if ( count( $nodes ) > 1 ) {
107 return $this->node( 'list', $nodes );
108 } else {
109 return $nodes[0];
110 }
111 }
112 /
113 and_or
114 )
115 {
116 return $this->node( 'complete_command', $list );
117 }
118
119 and_or =
120 first: pipeline
121 rest: (
122 AND_IF linebreak pipeline:pipeline
123 {
124 return $this->node( 'and_if', $pipeline );
125 }
126 / OR_IF linebreak pipeline:pipeline
127 {
128 return $this->node( 'or_if', $pipeline );
129 }
130 / pipeline
131 )*
132 {
133 return $this->merge( $first, $rest );
134 }
135
136 pipeline =
137 bang: Bang?
138 pipeline: pipe_sequence
139 {
140 if ( $bang !== null ) {
141 return $this->node( 'bang', $pipeline );
142 } else {
143 return $pipeline;
144 }
145 }
146
147 pipe_sequence =
148 first: command
149 rest: (
150 PIPE linebreak command:command
151 {
152 return $command;
153 }
154 )*
155 {
156 if ( count( $rest ) ) {
157 return $this->node( 'pipeline', $this->merge( $first, $rest ) );
158 } else {
159 return $first;
160 }
161 }
162
163 command =
164 function_definition
165 / simple_command
166 / c:compound_command r:redirect_list?
167 {
168 if ( $r !== null ) {
169 return $this->merge( $c, $r );
170 } else {
171 return $c;
172 }
173 }
174
175 compound_command =
176 brace_group
177 / subshell
178 / for_clause
179 / case_clause
180 / if_clause
181 / while_clause
182 / until_clause
183
184 subshell =
185 LPAREN list:compound_list RPAREN
186 {
187 return $this->node( 'subshell', $list );
188 }
189
190 compound_list =
191 linebreak
192 terms:(
193 term: and_or
194 separator: $separator
195 {
196 if ( $separator && $separator[0] === '&' ) {
197 return $this->node( 'background', $term );
198 } else {
199 return $term;
200 }
201 }
202 )+
203 last: and_or?
204 {
205 if ( $last ) {
206 $terms[] = $last;
207 }
208 return $terms;
209 }
210 /
211 linebreak
212 term: and_or
213 {
214 if ( $term === null ) {
215 // Phan is convinced $term may be null, not sure how
216 return [];
217 } else {
218 return $term;
219 }
220 }
221
222 for_clause =
223 (
224 For name:for_name linebreak for_case_in wordlist:wordlist? sequential_sep do_group:do_group
225 {
226 return $this->node( 'for', [ $name, $this->node( 'in', $wordlist ?: [] ), $do_group ] );
227 }
228 )
229 /
230 (
231 For name:for_name sequential_sep? do_group:do_group
232 {
233 return $this->node( 'for', [ $name, $do_group ] );
234 }
235 )
236
237 // Spec note: Apply rule 5.
238 // This and other lexer rules in the spec are mostly workarounds for loose
239 // integration between the lexer and the parser implied by the spec. We know
240 // that we want a NAME here, so we can just ask for a NAME. With a separate
241 // lexer it would be necessary for the lexer to guess whether the parser will
242 // want a NAME or a WORD, and for the parser to somehow downgrade an
243 // inappropriate NAME token to a WORD if the guess was wrong.
244 for_name = name:NAME OWS
245 {
246 return $name;
247 }
248
249 // Spec note: Apply rule 6
250 for_case_in = In OWS
251
252 wordlist = WORD+
253
254 case_clause =
255 Case word:WORD linebreak for_case_in linebreak list_esac:( case_list $Esac / case_list_ns $Esac / $Esac )
256 {
257 if ( is_array( $list_esac ) ) {
258 $list = $list_esac[0];
259 } else {
260 $list = [];
261 }
262 return $this->node( 'case', [ $word, $this->node( 'in', $list ) ] );
263 }
264
265 // ns means no semicolon
266 case_list_ns =
267 list:case_list item:case_item_ns
268 {
269 $list[] = $item;
270 return $list;
271 }
272 / item:case_item_ns
273 {
274 return [ $item ];
275 }
276
277 case_list =
278 case_item+
279
280 // ns means no semicolon
281 case_item_ns =
282 LPAREN? pattern:pattern RPAREN list:compound_list
283 {
284 return $this->node( 'case_item', [
285 $pattern,
286 $this->node( 'case_consequent', $list )
287 ] );
288 }
289 / LPAREN? pattern:pattern RPAREN linebreak
290 {
291 return $this->node( 'case_item', [ $pattern ] );
292 }
293
294 case_item =
295 LPAREN? pattern:pattern RPAREN list:compound_list DSEMI linebreak
296 {
297 return $this->node( 'case_item', [
298 $pattern,
299 $this->node( 'case_consequent', $list )
300 ] );
301 }
302 / LPAREN? pattern:pattern RPAREN linebreak DSEMI linebreak
303 {
304 return $this->node( 'case_item', $pattern );
305 }
306
307 // Spec note: rule 4
308 pattern =
309 first:WORD rest:( PIPE WORD )*
310 {
311 $patterns = [ $first ];
312 foreach ( $rest as $pattern ) {
313 $patterns[] = $pattern[1];
314 }
315 return $this->node( 'case_pattern', $patterns );
316 }
317
318 if_clause =
319 If
320 condition: compound_list
321 Then
322 consequent: compound_list
323 else_part: else_part?
324 Fi
325 {
326 $contents = [
327 $this->node( 'condition', $condition ),
328 $this->node( 'consequent', $consequent )
329 ];
330 if ( $else_part !== null ) {
331 $contents = $this->merge( $contents, $else_part );
332 }
333 return $this->node( 'if', $contents );
334 }
335
336 else_part =
337 Elif
338 condition: compound_list
339 Then
340 consequent: compound_list
341 else_part: else_part?
342 {
343 $contents = [
344 $this->node( 'elif_condition', $condition ),
345 $this->node( 'elif_consequent', $consequent )
346 ];
347 if ( $else_part !== null ) {
348 $contents = $this->merge( $contents, $else_part );
349 }
350 return $contents;
351 }
352 / Else alternative:compound_list
353 {
354 return [ $this->node( 'else', $alternative ) ];
355 }
356
357 while_clause =
358 While list:compound_list body:do_group
359 {
360 return $this->node( 'while', [
361 $this->node( 'condition', $list ),
362 $body
363 ] );
364 }
365
366 until_clause =
367 Until list:compound_list body:do_group
368 {
369 return $this->node( 'until', [
370 $this->node( 'condition', $list ),
371 $body
372 ] );
373 }
374
375 function_definition =
376 fname:fname LPAREN RPAREN linebreak body:function_body
377 {
378 return $this->node( 'function_definition',
379 $this->merge( $this->node( 'function_name', $fname ), $body ) );
380 }
381
382 // Spec note: Apply rule 9
383 function_body =
384 c:compound_command r:redirect_list?
385 {
386 if ( $r !== null ) {
387 return $this->merge( $c, $r );
388 } else {
389 return $c;
390 }
391 }
392
393 fname =
394 NAME // Apply rule 8
395
396 brace_group =
397 Lbrace list:compound_list Rbrace
398 {
399 return $this->node( 'brace_group', $list );
400 }
401
402 do_group =
403 Do list:compound_list Done // Apply rule 6
404 {
405 return $this->node( 'do', $list );
406 }
407
408 simple_command =
409 prefix:cmd_prefix word:cmd_word suffix:cmd_suffix?
410 {
411 $contents = [ $prefix, $word ];
412 if ( $suffix !== null ) {
413 $contents = array_merge( $contents, $suffix );
414 }
415 return $this->node( 'simple_command', $contents );
416 }
417 / prefix:cmd_prefix
418 {
419 return $this->node( 'simple_command', [ $prefix ] );
420 }
421 / name:cmd_name suffix:cmd_suffix?
422 {
423 $contents = [ $name ];
424 if ( $suffix ) {
425 $contents = array_merge( $contents, $suffix );
426 }
427 return $this->node( 'simple_command', $contents );
428 }
429
430 // Spec note: Apply rule 7a: Guess whether ASSIGNMENT_WORD is needed. That
431 // doesn't need any special handling, but we need to avoid allowing reserved
432 // words here with a negative assertion.
433 cmd_name =
434 !reserved word:WORD
435 {
436 return $word;
437 }
438
439 // Apply rule 7b
440 cmd_word =
441 WORD
442
443 cmd_prefix =
444 contents: (
445 io_redirect
446 / ASSIGNMENT_WORD
447 )+
448 {
449 return $this->node( 'cmd_prefix', $contents );
450 }
451
452 cmd_suffix =
453 (
454 io_redirect
455 / WORD
456 )+
457
458 redirect_list =
459 io_redirect+
460
461 io_redirect =
462 number:IO_NUMBER? file_or_here:(io_file / io_here)
463 {
464 $contents = [];
465 if ( $number !== null ) {
466 $contents[] = $this->node( 'io_subject', $number );
467 }
468 $contents[] = $file_or_here;
469 return $this->node( 'io_redirect', $contents );
470 }
471
472 // Options reordered to put the longer substrings first. Otherwise we would
473 // need assertions to protect longer operators from being partly consumed by
474 // smaller operators.
475 io_file =
476 LESSAND filename:filename
477 {
478 return $this->node( 'duplicate_input', $filename );
479 }
480 / LESSGREAT filename:filename
481 {
482 return $this->node( 'read_and_write', $filename );
483 }
484 / LESS filename:filename
485 {
486 return $this->node( 'input', $filename );
487 }
488 / GREATAND filename:filename
489 {
490 return $this->node( 'duplicate_output', $filename );
491 }
492 / DGREAT filename:filename
493 {
494 return $this->node( 'append_output', $filename );
495 }
496 / CLOBBER filename:filename
497 {
498 return $this->node( 'clobber', $filename );
499 }
500 / GREAT filename:filename
501 {
502 return $this->node( 'output', $filename );
503 }
504
505 filename =
506 WORD // Apply rule 2
507
508 io_here =
509 op: (
510 DLESSDASH { return 'io_here_strip'; }
511 / DLESS { return 'io_here'; }
512 )
513 end: here_end
514 { // @phan-suppress-previous-line PhanPluginNeverReturnMethod
515 // TODO: this is quite complicated to implement, especially given the way
516 // the parser is structured.
517 throw new UnimplementedError( 'heredoc is not implemented' );
518 // For phan
519 // @phan-suppress-next-line PhanPluginUnreachableCode
520 return $this->node( 'io_here', '' );
521 }
522
523 here_end =
524 $WORD // Apply rule 3
525
526 newline_list =
527 NEWLINE+
528
529 linebreak =
530 newline_list?
531
532 separator_op =
533 AND
534 / SEMI
535
536 separator =
537 separator_op linebreak
538 / newline_list
539
540 sequential_sep =
541 SEMI linebreak
542 / newline_list
543
544 // Operator tokens per spec
545
546 AND_IF = '&&' OWS
547 OR_IF = '||' OWS
548 DSEMI = ';;' OWS
549 DLESS = '<<' OWS
550 DGREAT = '>>' OWS
551 LESSAND = '<&' OWS
552 GREATAND = '>&' OWS
553 LESSGREAT = '<>' OWS
554 DLESSDASH = '<<-' OWS
555 CLOBBER = '>|' OWS
556
557 // Reserved word tokens per spec
558 If = 'if' DELIM
559 Then = 'then' DELIM
560 Else = 'else' DELIM
561 Elif = 'elif' DELIM
562 Fi = 'fi' DELIM
563 Do = 'do' DELIM
564 Done = 'done' DELIM
565 Case = 'case' DELIM
566 Esac = 'esac' DELIM
567 While = 'while' DELIM
568 Until = 'until' DELIM
569 For = 'for' DELIM
570 Lbrace = '{' DELIM
571 Rbrace = '}' DELIM
572 Bang = '!' DELIM
573 In = 'in' DELIM
574
575 reserved =
576 If
577 / Then
578 / Else
579 / Elif
580 / Fi
581 / Do
582 / Done
583 / Case
584 / Esac
585 / While
586 / Until
587 / For
588 / Lbrace
589 / Rbrace
590 / Bang
591 / In
592
593 // Single-character tokens with disambiguating assertions
594
595 AND = !AND_IF '&' OWS
596 SEMI = !DSEMI ';' OWS
597 LESS = !DLESS !LESSAND !LESSGREAT !DLESSDASH '<' OWS
598 GREAT = !DGREAT !GREATAND !CLOBBER '>' OWS
599 PIPE = !OR_IF '|' OWS
600 LPAREN = '(' OWS
601 RPAREN = ')' OWS
602
603 // Optional whitespace
604 // Consume whitespace and comments after each token
605 OWS = [ \t\v\r\f]* ("#" [^\n]*)?
606
607 // Delimiter assertion for reserved word termination
608 DELIM =
609 [ \t\v\r\f]+
610 / !. // EOF
611 / & "\n"
612
613 WORD =
614 parts: word_part+
615 OWS
616 {
617 return $this->node( 'word', $parts );
618 }
619
620 word_part =
621 single_quoted_part
622 / double_quoted_part
623 / bare_escape_sequence
624 / backquote_expansion
625 / dollar_expansion
626 / plain_part
627
628 single_quoted_part =
629 "'" contents:$[^']* "'"
630 {
631 return $this->node( 'single_quote', $contents );
632 }
633
634 double_quoted_part =
635 '"'
636 contents: (
637 dquoted_escape
638 / backquote_expansion
639 / dollar_expansion
640 / "\\"
641 / $[^"`$\\]+
642 )*
643 '"'
644 {
645 return $this->node( 'double_quote', $contents );
646 }
647
648 dquoted_escape =
649 "\\" contents:[$`"\\\n]
650 {
651 return $this->node( 'dquoted_escape', $contents );
652 }
653
654 bare_escape_sequence =
655 "\\" contents:[^\n]
656 {
657 return $this->node( 'bare_escape', $contents );
658 }
659
660 backquote_expansion =
661 "`"
662 parts: (
663 backquoted_escape
664 / dollar_expansion
665 / double_backquote_expansion
666 / "$"
667 / "\\"
668 / $[^`$\\]+
669 )*
670 "`"
671 {
672 return $this->node( 'backquote', $parts );
673 }
674
675 backquoted_escape =
676 "\\" contents:[$\\]
677 {
678 return $this->node( 'backquoted_escape', $contents );
679 }
680
681 double_backquote_expansion =
682 "\\`"
683 parts: (
684 backquoted_escape
685 / dollar_expansion
686 / "$"
687 / "\\" !"`"
688 / $[^`$\\]+
689 )
690 "\\`"
691 {
692 return $this->node( 'double_backquote', $parts );
693 }
694
695 dollar_expansion =
696 "$"
697 contents: (
698 special_parameter
699 / short_positional_parameter
700 / brace_expansion
701 / arithmetic_expansion
702 / command_expansion
703 / named_parameter
704 )
705 {
706 return $contents;
707 }
708
709 special_parameter =
710 contents: [@*#?\-$!0]
711 {
712 return $this->node( 'special_parameter', $contents );
713 }
714
715 short_positional_parameter =
716 contents: [1-9]
717 {
718 return $this->node( 'positional_parameter', $contents );
719 }
720
721 brace_expansion =
722 "{"
723 contents: (
724 binary_expansion
725 / string_length
726 / braced_parameter_expansion
727 )
728 "}"
729 {
730 return $contents;
731 }
732
733 binary_expansion =
734 parameter:parameter
735 operator:(
736 $( ":" [\-=?+] )
737 / $( "%%" / "##" / [%#\-=?+] )
738 )
739 OWS
740 word:WORD<no_rbrace>?
741 {
742 $names = [
743 ':-' => 'use_default',
744 '-' => 'use_default_unset',
745 ':=' => 'assign_default',
746 '=' => 'assign_default_unset',
747 ':?' => 'indicate_error',
748 '?' => 'indicate_error_unset',
749 ':+' => 'use_alternative',
750 '+' => 'use_alternative_unset',
751 '%' => 'remove_smallest_suffix',
752 '%%' => 'remove_largest_suffix',
753 '#' => 'remove_smallest_prefix',
754 '##' => 'remove_largest_prefix'
755 ];
756 if ( !isset( $names[$operator] ) ) {
757 throw new InternalError( "Unable to find operator \"$operator\"" );
758 }
759 return $this->node( $names[$operator], [ $parameter, $word ?? '' ] );
760 }
761
762 string_length =
763 "#" parameter:parameter
764 {
765 return $this->node( 'string_length', $parameter );
766 }
767
768 arithmetic_expansion =
769 "(("
770 OWS
771 words:WORD+
772 "))"
773 {
774 return $this->node( 'arithmetic_expansion', $words );
775 }
776
777 command_expansion =
778 "("
779 command: complete_command
780 ")"
781 {
782 return $this->node( 'command_expansion', $command );
783 }
784
785 braced_parameter_expansion =
786 parameter:parameter
787 {
788 return $this->node( 'braced_parameter_expansion', $parameter );
789 }
790
791 parameter =
792 special_parameter /
793 long_positional_parameter /
794 named_parameter
795
796 long_positional_parameter =
797 parameter: $[0-9]+
798 {
799 return $this->node( 'positional_parameter', $parameter );
800 }
801
802 named_parameter =
803 name:NAME
804 {
805 return $this->node( 'named_parameter', $name );
806 }
807
808 plain_part =
809 plain: (
810 $(&<no_rbrace> [^'"\\`$ \t\v\r\f\n&|;<>(){}]+)
811 / $(!<no_rbrace> [^'"\\`$ \t\v\r\f\n&|;<>()]+)
812 )
813 {
814 return $this->node( 'unquoted_literal', $plain );
815 }
816
817 ASSIGNMENT_WORD =
818 name:NAME "=" word:WORD
819 {
820 return $this->node( 'assignment', [ $this->node( 'name', $name ), $word ] );
821 }
822
823 NAME = $( [_a-zA-Z] [_a-zA-Z0-9]* )
824
825 NEWLINE = "\n" OWS
826
827 IO_NUMBER = $[0-9]+