-
-
Notifications
You must be signed in to change notification settings - Fork 147
/
cmd_parse.py
1576 lines (1263 loc) · 45.6 KB
/
cmd_parse.py
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
#!/usr/bin/env python
# Copyright 2016 Andy Chu. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
from __future__ import print_function
"""
cmd_parse.py - Parse high level shell commands.
"""
from asdl import const
from core import braces
from core import word
from core import util
from osh import match
from osh.meta import ast, Id, Kind, types
from osh.bool_parse import BoolParser
log = util.log
command_e = ast.command_e
word_e = ast.word_e
assign_op_e = ast.assign_op_e
lex_mode_e = types.lex_mode_e
class CommandParser(object):
"""
Args:
word_parse: to get a stream of words
lexer: for lookahead in function def, PushHint of ()
line_reader: for here doc
"""
def __init__(self, w_parser, lexer, line_reader, arena):
self.w_parser = w_parser # for normal parsing
self.lexer = lexer # for fast lookahead to (, for function defs
self.line_reader = line_reader # for here docs
self.arena = arena
self.Reset()
def Reset(self):
"""Reset our own internal state.
Called by the interactive loop.
"""
self.error_stack = []
self.completion_stack = []
# Cursor state set by _Peek()
self.next_lex_mode = lex_mode_e.OUTER
self.cur_word = None # current word
self.c_kind = Kind.Undefined
self.c_id = Id.Undefined_Tok
self.pending_here_docs = []
def ResetInputObjects(self):
"""Reset the internal state of our inputs.
Called by the interactive loop.
TODO: Should we just make new objects on every iteration?
"""
# All the stuff we read from
self.w_parser.Reset()
#self.lexer.Reset()
# TODO: This should be a method on Lexer. But I'm not sure if we want to
# reuse objects at all.
self.lexer.line_lexer.Reset('', -1)
self.line_reader.Reset()
def Error(self):
return self.error_stack
def _BadWord(self, msg, w):
"""Helper function for errors involving a word.
Args:
msg: format string with a single %s token
w: Word
"""
self.AddErrorContext(msg, w, word=w)
def AddErrorContext(self, msg, *args, **kwargs):
err = util.ParseError(msg, *args, **kwargs)
self.error_stack.append(err)
def GetCompletionState(self):
return self.completion_stack
def _MaybeReadHereDocs(self):
for h in self.pending_here_docs:
lines = []
#log('HERE %r' % h.here_end)
while True:
# If op is <<-, strip off all leading tabs (NOT spaces).
# (in C++, just bump the start?)
line_id, line = self.line_reader.GetLine()
#print("LINE %r %r" % (line, h.here_end))
if not line: # EOF
# An unterminated here doc is just a warning in bash. We make it
# fatal because we want to be strict, and because it causes problems
# reporting other errors.
# Attribute it to the << in <<EOF for now.
self.AddErrorContext('Unterminated here doc', span_id=h.spids[0])
return False
# NOTE: Could do this runtime to preserve LST.
if h.op_id == Id.Redir_DLessDash:
line = line.lstrip('\t')
if line.rstrip() == h.here_end:
break
lines.append((line_id, line))
parts = []
if h.do_expansion:
# NOTE: We read all lines at once, instead of doing it line-by-line,
# because of cases like this:
# cat <<EOF
# 1 $(echo 2
# echo 3) 4
# EOF
from osh import parse_lib # Avoid circular import
w_parser = parse_lib.MakeWordParserForHereDoc(lines, self.arena)
word = w_parser.ReadHereDocBody()
if not word:
self.AddErrorContext(
'Error reading here doc body: %s', w_parser.Error())
return False
h.body = word
h.was_filled = True
else:
# Each line is a single span. TODO: Add span_id to token.
tokens = [
ast.token(Id.Lit_Chars, line, const.NO_INTEGER)
for _, line in lines]
parts = [ast.LiteralPart(t) for t in tokens]
h.body = ast.CompoundWord(parts)
h.was_filled = True
# No .clear() until Python 3.3.
del self.pending_here_docs[:]
return True
def _Next(self, lex_mode=lex_mode_e.OUTER):
"""Helper method."""
self.next_lex_mode = lex_mode
def Peek(self):
"""Public method for REPL."""
if not self._Peek():
return None
return self.cur_word
def _Peek(self):
"""Helper method.
Returns True for success and False on error. Error examples: bad command
sub word, or unterminated quoted string, etc.
"""
if self.next_lex_mode != lex_mode_e.NONE:
w = self.w_parser.ReadWord(self.next_lex_mode)
if w is None:
error_stack = self.w_parser.Error()
self.error_stack.extend(error_stack)
return False
# Here docs only happen in command mode, so other kinds of newlines don't
# count.
if w.tag == word_e.TokenWord and w.token.id == Id.Op_Newline:
if not self._MaybeReadHereDocs():
return False
self.cur_word = w
self.c_kind = word.CommandKind(self.cur_word)
self.c_id = word.CommandId(self.cur_word)
self.next_lex_mode = lex_mode_e.NONE
#print('_Peek', self.cur_word)
return True
def _Eat(self, c_id):
"""Consume a word of a type. If it doesn't match, return False.
Args:
c_id: either EKeyword.* or a token type like Id.Right_Subshell.
TODO: Rationalize / type check this.
"""
if not self._Peek():
return False
# TODO: It would be nicer to print the word type, right now we get a number
if self.c_id != c_id:
self.AddErrorContext(
"Expected word type %s, got %s", c_id, self.cur_word,
word=self.cur_word)
return False
self._Next()
return True
def _NewlineOk(self):
"""Check for optional newline and consume it."""
if not self._Peek():
return False
if self.c_id == Id.Op_Newline:
self._Next()
if not self._Peek():
return False
return True
def ParseRedirect(self):
"""
Problem: You don't know which kind of redir_node to instantiate before
this? You could stuff them all in one node, and then have a switch() on
the type.
You need different types.
"""
if not self._Peek(): return None
assert self.c_kind == Kind.Redir, self.cur_word
left_spid = self.cur_word.token.span_id
# For now only supporting single digit descriptor
first_char = self.cur_word.token.val[0]
if first_char.isdigit():
fd = int(first_char)
else:
fd = const.NO_INTEGER
if self.c_id in (Id.Redir_DLess, Id.Redir_DLessDash): # here doc
node = ast.HereDoc()
node.op_id = self.c_id
node.body = None # not read yet
node.fd = fd
node.was_filled = False
node.spids.append(left_spid)
self._Next()
if not self._Peek(): return None
# "If any character in word is quoted, the delimiter shall be formed by
# performing quote removal on word, and the here-document lines shall not
# be expanded. Otherwise, the delimiter shall be the word itself."
# NOTE: \EOF counts, or even E\OF
ok, node.here_end, quoted = word.StaticEval(self.cur_word)
if not ok:
self._BadWord('Error evaluating here doc delimiter: %s', self.cur_word)
return None
node.do_expansion = not quoted
self._Next()
self.pending_here_docs.append(node) # will be filled on next newline.
else:
node = ast.Redir()
node.op_id = self.c_id
node.fd = fd
node.spids.append(left_spid)
self._Next()
if not self._Peek(): return None
if self.c_kind != Kind.Word:
self.AddErrorContext(
'Expected word after redirect operator', word=self.cur_word)
return None
new_word = word.TildeDetect(self.cur_word)
node.arg_word = new_word or self.cur_word
self._Next()
return node
def _ParseRedirectList(self):
"""Try parsing any redirects at the cursor.
This is used for blocks only, not commands.
Return None on error.
"""
redirects = []
while True:
if not self._Peek(): return None
# This prediction needs to ONLY accept redirect operators. Should we
# make them a separate TokeNkind?
if self.c_kind != Kind.Redir:
break
node = self.ParseRedirect()
if not node:
return None
redirects.append(node)
self._Next()
return redirects
def _ScanSimpleCommand(self):
"""First pass: Split into redirects and words."""
redirects = []
words = []
while True:
if not self._Peek(): return None
if self.c_kind == Kind.Redir:
node = self.ParseRedirect()
if not node: return None # e.g. EOF
redirects.append(node)
elif self.c_kind == Kind.Word:
words.append(self.cur_word)
else:
break
self._Next()
return redirects, words
def _SplitSimpleCommandPrefix(self, words):
"""
Second pass of SimpleCommand parsing: look for assignment words.
"""
prefix_bindings = []
suffix_words = []
done_prefix = False
for w in words:
if done_prefix:
suffix_words.append(w)
continue
left_spid = word.LeftMostSpanForWord(w)
kov = word.LooksLikeAssignment(w)
if kov:
k, op, v = kov
t = word.TildeDetect(v)
if t:
# t is an unevaluated word with TildeSubPart
prefix_bindings.append((k, op, t, left_spid))
else:
prefix_bindings.append((k, op, v, left_spid)) # v is unevaluated word
else:
done_prefix = True
suffix_words.append(w)
return prefix_bindings, suffix_words
def _MakeSimpleCommand(self, prefix_bindings, suffix_words, redirects):
# FOO=(1 2 3) ls is not allowed
for k, _, v, _ in prefix_bindings:
if word.HasArrayPart(v):
self.AddErrorContext(
'Unexpected array literal in binding: %s', v, word=v)
return None
# echo FOO=(1 2 3) is not allowed
# NOTE: Other checks can be inserted here. Can resolve builtins,
# functions, aliases, static PATH, etc.
for w in suffix_words:
kov = word.LooksLikeAssignment(w)
if kov:
_, _, v = kov
if word.HasArrayPart(v):
self.AddErrorContext('Unexpected array literal: %s', v, word=w)
return None
# NOTE: # In bash, {~bob,~jane}/src works, even though ~ isn't the leading
# character of the initial word.
# However, this means we must do tilde detection AFTER brace EXPANSION, not
# just after brace DETECTION like we're doing here.
# The BracedWordTree instances have to be expanded into CompoundWord
# instances for the tilde detection to work.
words2 = braces.BraceDetectAll(suffix_words)
words3 = word.TildeDetectAll(words2)
node = ast.SimpleCommand()
node.words = words3
node.redirects = redirects
for name, op, val, left_spid in prefix_bindings:
if op != assign_op_e.Equal:
# NOTE: Using spid of RHS for now, since we don't have one for op.
self.AddErrorContext('Expected = in environment binding, got +=',
word=val)
return None
pair = ast.env_pair(name, val)
pair.spids.append(left_spid)
node.more_env.append(pair)
return node
def _MakeAssignment(self, assign_kw, suffix_words):
# First parse flags, e.g. -r -x -a -A. None of the flags have arguments.
flags = []
n = len(suffix_words)
i = 1
while i < n:
w = suffix_words[i]
ok, static_val, quoted = word.StaticEval(w)
if not ok or quoted:
break # can't statically evaluate
if static_val.startswith('-'):
flags.append(static_val)
else:
break # not a flag, rest are args
i += 1
# Now parse bindings or variable names
assignments = []
while i < n:
w = suffix_words[i]
left_spid = word.LeftMostSpanForWord(w)
kov = word.LooksLikeAssignment(w)
if kov:
k, op, v = kov
t = word.TildeDetect(v)
if t:
# t is an unevaluated word with TildeSubPart
a = (k, op, t, left_spid)
else:
a = (k, op, v, left_spid) # v is unevaluated word
else:
# In aboriginal in variables/sources: export_if_blank does export "$1".
# We should allow that.
# Parse this differently then?
# dynamic-export?
# It sets global variables.
ok, static_val, quoted = word.StaticEval(w)
if not ok or quoted:
self.AddErrorContext(
'Variable names must be constant strings, got %s', w, word=w)
return None
# No value is equivalent to ''
if not match.IsValidVarName(static_val):
self.AddErrorContext('Invalid variable name %r', static_val, word=w)
return None
a = (static_val, assign_op_e.Equal, None, left_spid)
assignments.append(a)
i += 1
# TODO: Also make with LhsIndexedName
pairs = []
for lhs, op, rhs, spid in assignments:
p = ast.assign_pair(ast.LhsName(lhs), op, rhs)
p.spids.append(spid)
pairs.append(p)
node = ast.Assignment(assign_kw, flags, pairs)
return node
# Flags that indicate an assignment should be parsed like a command.
_ASSIGN_COMMANDS = set([
(Id.Assign_Declare, '-f'), # function defs
(Id.Assign_Declare, '-F'), # function names
(Id.Assign_Declare, '-p'), # print
(Id.Assign_Typeset, '-f'),
(Id.Assign_Typeset, '-F'),
(Id.Assign_Typeset, '-p'),
(Id.Assign_Local, '-p'),
(Id.Assign_Readonly, '-p'),
# Hm 'export -p' is more like a command. But we're parsing it
# dynamically now because of some wrappers.
# Maybe we could change this.
#(Id.Assign_Export, '-p'),
])
# Flags to parse like assignments: -a -r -x (and maybe -i)
def ParseSimpleCommand(self):
"""
Fixed transcription of the POSIX grammar (TODO: port to grammar/Shell.g)
io_file : '<' filename
| LESSAND filename
...
io_here : DLESS here_end
| DLESSDASH here_end
redirect : IO_NUMBER (io_redirect | io_here)
prefix_part : ASSIGNMENT_WORD | redirect
cmd_part : WORD | redirect
assign_kw : Declare | Export | Local | Readonly
# Without any words it is parsed as a command, not an assigment
assign_listing : assign_kw
# Now we have something to do (might be changing assignment flags too)
# NOTE: any prefixes should be a warning, but they are allowed in shell.
assignment : prefix_part* assign_kw (WORD | ASSIGNMENT_WORD)+
# an external command, a function call, or a builtin -- a "word_command"
word_command : prefix_part* cmd_part+
simple_command : assign_listing
| assignment
| proc_command
Simple imperative algorithm:
1) Read a list of words and redirects. Append them to separate lists.
2) Look for the first non-assignment word. If it's declare, etc., then
keep parsing words AND assign words. Otherwise, just parse words.
3) If there are no non-assignment words, then it's a global assignment.
{ redirects, global assignments } OR
{ redirects, prefix_bindings, words } OR
{ redirects, ERROR_prefix_bindings, keyword, assignments, words }
THEN CHECK that prefix bindings don't have any array literal parts!
global assignment and keyword assignments can have the of course.
well actually EXPORT shouldn't have them either -- WARNING
3 cases we want to warn: prefix_bindings for assignment, and array literal
in prefix bindings, or export
A command can be an assignment word, word, or redirect on its own.
ls
>out.txt
>out.txt FOO=bar # this touches the file, and hten
Or any sequence:
ls foo bar
<in.txt ls foo bar >out.txt
<in.txt ls >out.txt foo bar
Or add one or more environment bindings:
VAR=val env
>out.txt VAR=val env
here_end vs filename is a matter of whether we test that it's quoted. e.g.
<<EOF vs <<'EOF'.
"""
result = self._ScanSimpleCommand()
if not result: return None
redirects, words = result
if not words: # e.g. >out.txt # redirect without words
node = ast.SimpleCommand()
node.redirects = redirects
return node
prefix_bindings, suffix_words = self._SplitSimpleCommandPrefix(words)
if not suffix_words: # ONE=1 TWO=2 (with no other words)
if redirects:
binding1 = prefix_bindings[0]
_, _, _, spid = binding1
self.AddErrorContext('Got redirects in global assignment',
span_id=spid)
return None
pairs = []
for lhs, op, rhs, spid in prefix_bindings:
p = ast.assign_pair(ast.LhsName(lhs), op, rhs)
p.spids.append(spid)
pairs.append(p)
node = ast.Assignment(Id.Assign_None, [], pairs)
left_spid = word.LeftMostSpanForWord(words[0])
node.spids.append(left_spid) # no keyword spid to skip past
return node
kind, kw_token = word.KeywordToken(suffix_words[0])
if kind == Kind.Assign:
# Here we StaticEval suffix_words[1] to see if it's a command like
# 'typeset -p'. Then it becomes a SimpleCommand node instead of an
# Assignment. Note we're not handling duplicate flags like 'typeset
# -pf'. I see this in bashdb (bash debugger) but it can just be changed
# to 'typeset -p -f'.
is_command = False
if len(suffix_words) > 1:
ok, val, _ = word.StaticEval(suffix_words[1])
if ok and (kw_token.id, val) in self._ASSIGN_COMMANDS:
is_command = True
if is_command: # declare -f, declare -p, typeset -p, etc.
node = self._MakeSimpleCommand(prefix_bindings, suffix_words,
redirects)
return node
else: # declare str='', declare -a array=()
if redirects:
# Attach the error location to the keyword. It would be more precise
# to attach it to the
self.AddErrorContext('Got redirects in assignment', token=kw_token)
return None
if prefix_bindings: # FOO=bar local spam=eggs not allowed
# Use the location of the first value. TODO: Use the whole word
# before splitting.
_, _, v0, _ = prefix_bindings[0]
self.AddErrorContext(
'Invalid prefix bindings in assignment: %s', prefix_bindings,
word=v0)
return None
node = self._MakeAssignment(kw_token.id, suffix_words)
if not node: return None
node.spids.append(kw_token.span_id)
return node
elif kind == Kind.ControlFlow:
if redirects:
self.AddErrorContext('Got redirects in control flow: %s', redirects)
return None
if prefix_bindings: # FOO=bar local spam=eggs not allowed
# Use the location of the first value. TODO: Use the whole word before
# splitting.
_, _, v0, _ = prefix_bindings[0]
self.AddErrorContext(
'Invalid prefix bindings in control flow: %s', prefix_bindings,
word=v0)
return None
# Attach the token for errors. (Assignment may not need it.)
if len(suffix_words) == 1:
arg_word = None
elif len(suffix_words) == 2:
arg_word = suffix_words[1]
else:
# Underline the extra word.
self.AddErrorContext(
'Unexpected argument to %r', kw_token.val, word=suffix_words[2])
return None
return ast.ControlFlow(kw_token, arg_word)
else:
node = self._MakeSimpleCommand(prefix_bindings, suffix_words, redirects)
return node
def ParseBraceGroup(self):
"""
brace_group : LBrace command_list RBrace ;
"""
left_spid = word.LeftMostSpanForWord(self.cur_word)
if not self._Eat(Id.Lit_LBrace): return None
c_list = self.ParseCommandList()
if not c_list: return None
# Not needed
#right_spid = word.LeftMostSpanForWord(self.cur_word)
if not self._Eat(Id.Lit_RBrace): return None
node = ast.BraceGroup(c_list.children)
node.spids.append(left_spid)
return node
def ParseDoGroup(self):
"""
Used by ForEach, ForExpr, While, Until. Should this be a Do node?
do_group : Do command_list Done ; /* Apply rule 6 */
"""
if not self._Eat(Id.KW_Do): return None
do_spid = word.LeftMostSpanForWord(self.cur_word) # after _Eat
c_list = self.ParseCommandList() # could be any thing
if not c_list: return None
if not self._Eat(Id.KW_Done): return None
done_spid = word.LeftMostSpanForWord(self.cur_word) # after _Eat
node = ast.DoGroup(c_list.children)
node.spids.extend((do_spid, done_spid))
return node
def ParseForWords(self):
"""
for_words : WORD* for_sep
;
for_sep : ';' newline_ok
| NEWLINES
;
"""
words = []
# The span_id of any semi-colon, so we can remove it.
semi_spid = const.NO_INTEGER
while True:
if not self._Peek(): return None
if self.c_id == Id.Op_Semi:
semi_spid = self.cur_word.token.span_id # TokenWord
self._Next()
if not self._NewlineOk(): return None
break
elif self.c_id == Id.Op_Newline:
self._Next()
break
if self.cur_word.tag != word_e.CompoundWord:
# TODO: Can we also show a pointer to the 'for' keyword?
self.AddErrorContext('Invalid word in for loop', word=self.cur_word)
return None
words.append(self.cur_word)
self._Next()
return words, semi_spid
def _ParseForExprLoop(self):
"""
for (( init; cond; update )) for_sep? do_group
"""
node = self.w_parser.ReadForExpression()
if not node:
error_stack = self.w_parser.Error()
self.error_stack.extend(error_stack)
self.AddErrorContext("Parsing for expression failed")
return None
self._Next()
if not self._Peek(): return None
if self.c_id == Id.Op_Semi:
self._Next()
if not self._NewlineOk(): return None
elif self.c_id == Id.Op_Newline:
self._Next()
elif self.c_id == Id.KW_Do: # missing semicolon/newline allowed
pass
else:
self.AddErrorContext(
'Unexpected token after for expression: %s', self.cur_word,
word=self.cur_word)
return None
body_node = self.ParseDoGroup()
if not body_node: return None
node.body = body_node
return node
def _ParseForEachLoop(self):
node = ast.ForEach()
node.do_arg_iter = False
ok, iter_name, quoted = word.StaticEval(self.cur_word)
if not ok or quoted:
self.AddErrorContext(
"Invalid for loop variable", word=self.cur_word)
return None
if not match.IsValidVarName(iter_name):
self.AddErrorContext(
"Invalid for loop variable name", word=self.cur_word)
return None
node.iter_name = iter_name
self._Next() # skip past name
if not self._NewlineOk(): return None
in_spid = const.NO_INTEGER
semi_spid = const.NO_INTEGER
if not self._Peek(): return None
if self.c_id == Id.KW_In:
self._Next() # skip in
in_spid = word.LeftMostSpanForWord(self.cur_word) + 1
x = self.ParseForWords()
if x is None:
return None
iter_words, semi_spid = x
words2 = braces.BraceDetectAll(iter_words)
words3 = word.TildeDetectAll(words2)
if iter_words is None: # empty list of words is OK
return None
node.iter_words = words3
elif self.c_id == Id.Op_Semi:
node.do_arg_iter = True # implicit for loop
self._Next()
elif self.c_id == Id.KW_Do:
node.do_arg_iter = True # implicit for loop
# do not advance
else:
self.AddErrorContext("Unexpected word in for loop: %s", self.cur_word,
word=self.cur_word)
return None
node.spids.extend((in_spid, semi_spid))
body_node = self.ParseDoGroup()
if not body_node: return None
node.body = body_node
return node
def ParseFor(self):
"""
for_clause : For for_name newline_ok (in for_words? for_sep)? do_group ;
| For '((' ... TODO
"""
if not self._Eat(Id.KW_For): return None
if not self._Peek(): return None
if self.c_id == Id.Op_DLeftParen:
node = self._ParseForExprLoop()
else:
node = self._ParseForEachLoop()
return node
def ParseWhile(self):
"""
while_clause : While command_list do_group ;
"""
self._Next() # skip while
cond_node = self.ParseCommandList()
if not cond_node: return None
body_node = self.ParseDoGroup()
if not body_node: return None
return ast.While(cond_node.children, body_node)
def ParseUntil(self):
"""
until_clause : Until command_list do_group ;
"""
self._Next() # skip until
cond_node = self.ParseCommandList()
if not cond_node: return None
body_node = self.ParseDoGroup()
if not body_node: return None
return ast.Until(cond_node.children, body_node)
def ParseCaseItem(self):
"""
case_item: '('? pattern ('|' pattern)* ')'
newline_ok command_term? trailer? ;
"""
self.lexer.PushHint(Id.Op_RParen, Id.Right_CasePat)
left_spid = word.LeftMostSpanForWord(self.cur_word)
if self.c_id == Id.Op_LParen:
self._Next()
pat_words = []
while True:
if not self._Peek(): return None
pat_words.append(self.cur_word)
self._Next()
if not self._Peek(): return None
if self.c_id == Id.Op_Pipe:
self._Next()
else:
break
rparen_spid = word.LeftMostSpanForWord(self.cur_word)
if not self._Eat(Id.Right_CasePat): return None
if not self._NewlineOk(): return None
if self.c_id not in (Id.Op_DSemi, Id.KW_Esac):
c_list = self.ParseCommandTerm()
if not c_list: return None
action_children = c_list.children
else:
action_children = []
dsemi_spid = const.NO_INTEGER
last_spid = const.NO_INTEGER
if not self._Peek(): return None
if self.c_id == Id.KW_Esac:
last_spid = word.LeftMostSpanForWord(self.cur_word)
elif self.c_id == Id.Op_DSemi:
dsemi_spid = word.LeftMostSpanForWord(self.cur_word)
self._Next()
else:
self.AddErrorContext('Expected DSEMI or ESAC, got %s', self.cur_word,
word=self.cur_word)
return None
if not self._NewlineOk(): return None
arm = ast.case_arm(pat_words, action_children)
arm.spids.extend((left_spid, rparen_spid, dsemi_spid, last_spid))
return arm
def ParseCaseList(self, arms):
"""
case_list: case_item (DSEMI newline_ok case_item)* DSEMI? newline_ok;
"""
if not self._Peek(): return None
while True:
# case item begins with a command word or (
if self.c_id == Id.KW_Esac:
break
if self.c_kind != Kind.Word and self.c_id != Id.Op_LParen:
break
arm = self.ParseCaseItem()
if not arm: return None
arms.append(arm)
if not self._Peek(): return None
# Now look for DSEMI or ESAC
return True
def ParseCase(self):
"""
case_clause : Case WORD newline_ok in newline_ok case_list? Esac ;
"""
case_node = ast.Case()
case_spid = word.LeftMostSpanForWord(self.cur_word)
self._Next() # skip case
if not self._Peek(): return None
case_node.to_match = self.cur_word
self._Next()
if not self._NewlineOk(): return None
in_spid = word.LeftMostSpanForWord(self.cur_word)
if not self._Eat(Id.KW_In): return None
if not self._NewlineOk(): return None
if self.c_id != Id.KW_Esac: # empty case list
if not self.ParseCaseList(case_node.arms):
self.AddErrorContext("ParseCase: error parsing case list")
return None
# TODO: should it return a list of nodes, and extend?
if not self._Peek(): return None
esac_spid = word.LeftMostSpanForWord(self.cur_word)
if not self._Eat(Id.KW_Esac): return None
self._Next()
case_node.spids.extend((case_spid, in_spid, esac_spid))
return case_node
def _ParseElifElse(self, if_node):
"""
else_part: (Elif command_list Then command_list)* Else command_list ;
"""
arms = if_node.arms
self._Peek()
while self.c_id == Id.KW_Elif:
elif_spid = word.LeftMostSpanForWord(self.cur_word)
self._Next() # skip elif
cond = self.ParseCommandList()
if not cond: return None
then_spid = word.LeftMostSpanForWord(self.cur_word)
if not self._Eat(Id.KW_Then): return None
body = self.ParseCommandList()
if not body: return None
arm = ast.if_arm(cond.children, body.children)
arm.spids.extend((elif_spid, then_spid))
arms.append(arm)
if self.c_id == Id.KW_Else:
else_spid = word.LeftMostSpanForWord(self.cur_word)
self._Next()
body = self.ParseCommandList()
if not body: return None
if_node.else_action = body.children
else:
else_spid = const.NO_INTEGER
if_node.spids.append(else_spid)
return True
def ParseIf(self):
"""
if_clause : If command_list Then command_list else_part? Fi ;
"""
if_node = ast.If()
self._Next() # skip if
cond = self.ParseCommandList()
if not cond: return None