OILS / tools / ysh_ify.py View on Github | oilshell.org

1121 lines, 575 significant
1from __future__ import print_function
2"""
3ysh_ify.py: Roughly translate OSH to YSH. Doesn't respect semantics.
4
5ESSENTIAL
6
7Command:
8
9 then/fi, do/done -> { }
10
11 new case statement
12
13 f() { } -> proc f { } (changes scope)
14
15 subshell -> forkwait, because () is taken
16 { } to fopen { }?
17
18 Approximate: var declaration:
19 local a=b -> var a = 'b', I think
20
21 <<EOF here docs to '''
22
23Word:
24 "$@" -> @ARGV
25
26 Not common: unquoted $x -> @[split(x)]
27
28LEGACY that I don't personally use
29
30Builtins:
31 [ -> test
32 . -> source
33
34Word:
35 backticks -> $() (I don't use this)
36 quote removal "$foo" -> $foo
37 brace removal ${foo} and "${foo}" -> $foo
38
39--tool format
40
41 fix indentation and spacing, like clang-format
42 can "lower" the LST to a rough representation with keywords / "first words",
43 { } ( ), and comments
44 - the "atoms" should not have newlines
45"""
46
47from _devbuild.gen.id_kind_asdl import Id, Id_str
48from _devbuild.gen.runtime_asdl import word_style_e, word_style_t
49from _devbuild.gen.syntax_asdl import (
50 loc,
51 CompoundWord,
52 Token,
53 SimpleVarSub,
54 BracedVarSub,
55 CommandSub,
56 DoubleQuoted,
57 SingleQuoted,
58 word_e,
59 word_t,
60 word_part,
61 word_part_e,
62 word_part_t,
63 rhs_word_e,
64 rhs_word_t,
65 sh_lhs,
66 sh_lhs_e,
67 command,
68 command_e,
69 BraceGroup,
70 for_iter_e,
71 case_arg_e,
72 case_arg,
73 condition,
74 condition_e,
75 redir_param,
76 redir_param_e,
77 Redir,
78)
79from asdl import runtime
80from core.error import p_die
81from frontend import lexer
82from frontend import location
83from osh import word_
84from mycpp import mylib
85from mycpp.mylib import log, print_stderr, tagswitch
86
87from typing import Dict, cast, TYPE_CHECKING
88if TYPE_CHECKING:
89 from _devbuild.gen.syntax_asdl import command_t
90 from core import alloc
91
92_ = log
93
94
95class Cursor(object):
96 """
97 API to print/transform a complete source file, stored in a single arena.
98
99 In, core/alloc.py, SnipCodeBlock() and SnipCodeString work on lines. They
100 don't iterate over tokens.
101
102 Or add a separate hash table of Token -> span ID? That makes sense because
103 we need that kind of "address hash" for type checking anyway.
104
105 You use the hash table to go from next_token_id .. TokenId(until_token).
106 """
107
108 def __init__(self, arena, f):
109 # type: (alloc.Arena, mylib.Writer) -> None
110 self.arena = arena
111 self.f = f
112 self.next_span_id = 0
113
114 def _PrintUntilSpid(self, until_span_id):
115 # type: (int) -> None
116
117 # Sometimes we add +1
118 if until_span_id == runtime.NO_SPID:
119 assert 0, 'Missing span ID, got %d' % until_span_id
120
121 for span_id in xrange(self.next_span_id, until_span_id):
122 span = self.arena.GetToken(span_id)
123
124 # A span for Eof may not have a line when the file is completely empty.
125 if span.line is None:
126 continue
127
128 # Special case for recovering stripped leading space!
129 # See osh/word_compile.py
130 start_index = (0 if span.id == Id.Lit_CharsWithoutPrefix else
131 span.col)
132 end_index = span.col + span.length
133
134 piece = span.line.content[start_index:end_index]
135 self.f.write(piece)
136
137 self.next_span_id = until_span_id
138
139 def _SkipUntilSpid(self, next_span_id):
140 # type: (int) -> None
141 """Skip everything before next_span_id.
142
143 Printing will start at next_span_id
144 """
145 if (next_span_id == runtime.NO_SPID or
146 next_span_id == runtime.NO_SPID + 1):
147 assert 0, 'Missing span ID, got %d' % next_span_id
148 self.next_span_id = next_span_id
149
150 def SkipUntil(self, tok):
151 # type: (Token) -> None
152 span_id = self.arena.GetSpanId(tok)
153 self._SkipUntilSpid(span_id)
154
155 def SkipPast(self, tok):
156 # type: (Token) -> None
157 span_id = self.arena.GetSpanId(tok)
158 self._SkipUntilSpid(span_id + 1)
159
160 def PrintUntil(self, tok):
161 # type: (Token) -> None
162 span_id = self.arena.GetSpanId(tok)
163
164 # Test invariant
165 if mylib.PYTHON:
166 arena_tok = self.arena.GetToken(span_id)
167 if tok != arena_tok:
168 raise AssertionError(
169 '%s %d %d != %s %d %d' %
170 (tok, span_id, id(tok), arena_tok,
171 self.arena.GetSpanId(arena_tok), id(arena_tok)))
172
173 self._PrintUntilSpid(span_id)
174
175 def PrintIncluding(self, tok):
176 # type: (Token) -> None
177 span_id = self.arena.GetSpanId(tok)
178 self._PrintUntilSpid(span_id + 1)
179
180 def PrintUntilEnd(self):
181 # type: () -> None
182 self._PrintUntilSpid(self.arena.LastSpanId())
183
184
185def LosslessCat(arena):
186 # type: (alloc.Arena) -> None
187 """
188 For testing the lossless invariant: the tokens "add up" to the original
189 doc.
190 """
191 cursor = Cursor(arena, mylib.Stdout())
192 cursor.PrintUntilEnd()
193
194
195def PrintTokens(arena):
196 # type: (alloc.Arena) -> None
197 """Debugging tool to see tokens."""
198
199 if len(arena.tokens) == 1: # Special case for line_id == -1
200 print('Empty file with EOF token on invalid line:')
201 print('%s' % arena.tokens[0])
202 return
203
204 for i, tok in enumerate(arena.tokens):
205 piece = tok.line.content[tok.col:tok.col + tok.length]
206 print('%5d %-20s %r' % (i, Id_str(tok.id), piece))
207 print_stderr('(%d tokens)' % len(arena.tokens))
208
209
210def Ysh_ify(arena, node):
211 # type: (alloc.Arena, command_t) -> None
212 cursor = Cursor(arena, mylib.Stdout())
213 fixer = YshPrinter(cursor, arena, mylib.Stdout())
214 fixer.DoCommand(node, None, at_top_level=True) # no local symbols yet
215 fixer.End()
216
217
218# PROBLEM: ~ substitution. That is disabled by "".
219# You can turn it into $HOME I guess
220# const foo = "$HOME/src"
221# const foo = %( ~/src )[0] # does this make sense?
222
223
224def _GetRhsStyle(w):
225 # type: (rhs_word_t) -> word_style_t
226 """Determine what style an assignment should use. '' or "", or an
227 expression.
228
229 SQ foo= setglobal foo = ''
230 SQ foo='' setglobal foo = ''
231 DQ foo="" setglobal foo = "" # Or we could normalize it if no subs?
232 DQ foo="" setglobal foo = "" # Or we could normalize it if no subs?
233
234 # Need these too.
235 # Or honestly should C strings be the default? And then raw strings are
236 # optional? Because most usages of \n and \0 can turn into Oil?
237 # Yeah I want the default to be statically parseable, so we subvert the \t
238 # and \n of command line tools?
239 # As long as we are fully analyzing the strings, we might as well go all the
240 # way!
241 # I think I need a PartialStaticEval() to paper over this.
242 #
243 # The main issue is regex and globs, because they use escape for a different
244 # purpose. I think just do
245 # grep r'foo\tbar' or something.
246
247 C_SQ foo=$'\n' setglobal foo = C'\n'
248 C_DQ foo=$'\n'"$bar" setglobal foo = C"\n$(bar)"
249
250 Expr path=${1:-} setglobal path = $1 or ''
251 Expr host=${2:-$(hostname)} setglobal host = $2 or $[hostname]
252
253 What's the difference between Expr and Unquoted? I think they're the same/
254 """
255 # Actually splitting NEVER HAPPENS ON ASSIGNMENT. LEAVE IT OFF.
256
257 UP_w = w
258 with tagswitch(w) as case:
259 if case(rhs_word_e.Empty):
260 return word_style_e.SQ
261
262 elif case(rhs_word_e.Compound):
263 w = cast(CompoundWord, UP_w)
264 if len(w.parts) == 0:
265 raise AssertionError(w)
266
267 elif len(w.parts) == 1:
268 part0 = w.parts[0]
269 UP_part0 = part0
270 with tagswitch(part0) as case:
271 # VAR_SUBS
272 if case(word_part_e.TildeSub):
273 # x=~andy/src
274 # -> setvar x = homedir('andy') + '/src'
275 return word_style_e.Expr
276
277 elif case(word_part_e.Literal):
278 # local x=y
279 # -> var x = 'y'
280 return word_style_e.SQ
281
282 elif case(word_part_e.SimpleVarSub):
283 # local x=$myvar
284 # -> var x = "$myvar"
285 # or var x = ${myvar}
286 # or var x = myvar
287 return word_style_e.DQ
288
289 elif case(word_part_e.BracedVarSub, word_part_e.CommandSub,
290 word_part_e.ArithSub):
291 # x=$(hostname)
292 # -> setvar x = $(hostname)
293 return word_style_e.Unquoted
294
295 elif case(word_part_e.DoubleQuoted):
296 part0 = cast(DoubleQuoted, UP_part0)
297
298 # TODO: remove quotes in single part like "$(hostname)" -> $(hostname)
299 return word_style_e.DQ
300
301 else:
302 # multiple parts use YSTR in general?
303 # Depends if there are subs
304 return word_style_e.DQ
305
306 # Default
307 return word_style_e.SQ
308
309
310class YshPrinter(object):
311 """Prettify OSH to YSH."""
312
313 def __init__(self, cursor, arena, f):
314 # type: (Cursor, alloc.Arena, mylib.Writer) -> None
315 self.cursor = cursor
316 self.arena = arena
317 self.f = f
318
319 def _DebugSpid(self, spid):
320 # type: (int) -> None
321 span = self.arena.GetToken(spid)
322 s = span.line.content[span.col:span.col + span.length]
323 print_stderr('SPID %d = %r' % (spid, s))
324
325 def End(self):
326 # type: () -> None
327 """Make sure we print until the end of the file."""
328 self.cursor.PrintUntilEnd()
329
330 def DoRedirect(self, node, local_symbols):
331 # type: (Redir, Dict[str, bool]) -> None
332 """
333 Currently Unused
334 TODO: It would be nice to change here docs to <<< '''
335 """
336 #print(node, file=sys.stderr)
337 op_id = node.op.id
338 self.cursor.PrintUntil(node.op)
339
340 if node.arg.tag() == redir_param_e.HereDoc:
341 here_doc = cast(redir_param.HereDoc, node.arg)
342
343 here_begin = here_doc.here_begin
344 ok, delimiter, delim_quoted = word_.StaticEval(here_begin)
345 if not ok:
346 p_die('Invalid here doc delimiter', loc.Word(here_begin))
347
348 # Turn everything into <<<. We just change the quotes
349 self.f.write('<<<')
350
351 if delim_quoted:
352 self.f.write(" '''")
353 else:
354 self.f.write(' """')
355
356 delim_end_tok = location.RightTokenForWord(here_begin)
357 self.cursor.SkipPast(delim_end_tok)
358
359 # Now print the lines. TODO: Have a flag to indent these to the level of
360 # the owning command, e.g.
361 # cat <<EOF
362 # EOF
363 # Or since most here docs are the top level, you could just have a hack
364 # for a fixed indent? TODO: Look at real use cases.
365 for part in here_doc.stdin_parts:
366 self.DoWordPart(part, local_symbols)
367
368 self.cursor.SkipPast(here_doc.here_end_tok)
369 if delim_quoted:
370 self.f.write("'''\n")
371 else:
372 self.f.write('"""\n')
373
374 else:
375 pass
376
377 # cat << EOF
378 # hello $name
379 # EOF
380 # cat <<< """
381 # hello $name
382 # """
383
384 # cat << 'EOF'
385 # no expansion
386 # EOF
387
388 # cat <<< '''
389 # no expansion
390 # '''
391
392 def DoShAssignment(self, node, at_top_level, local_symbols):
393 # type: (command.ShAssignment, bool, Dict[str, bool]) -> None
394 """
395 local_symbols:
396 - Add every 'local' declaration to it
397 - problem: what if you have local in an "if" ?
398 - we could treat it like nested scope and see what happens? Do any
399 programs have a problem with it?
400 case/if/for/while/BraceGroup all define scopes or what?
401 You don't want inconsistency of variables that could be defined at
402 any point.
403 - or maybe you only need it within "if / case" ? Well I guess
404 for/while can break out of the loop and cause problems. A break is
405 an "if".
406
407 - for subsequent
408 """
409 # Change RHS to expression language. Bare words not allowed. foo -> 'foo'
410
411 has_rhs = False # TODO: Should be on a per-variable basis.
412 # local a=b c=d, or just punt on those
413 defined_locally = False # is it a local variable in this function?
414 # can't tell if global
415
416 if True:
417 self.cursor.PrintUntil(node.pairs[0].left)
418
419 # For now, just detect whether the FIRST assignment on the line has been
420 # declared locally. We might want to split every line into separate
421 # statements.
422 if local_symbols is not None:
423 lhs0 = node.pairs[0].lhs
424 #if lhs0.tag() == sh_lhs_e.Name and lhs0.name in local_symbols:
425 # defined_locally = True
426
427 #print("CHECKING NAME", lhs0.name, defined_locally, local_symbols)
428
429 # TODO: Avoid translating these
430 has_array_index = [
431 pair.lhs.tag() == sh_lhs_e.UnparsedIndex for pair in node.pairs
432 ]
433
434 # need semantic analysis.
435 # Would be nice to assume that it's a local though.
436 if at_top_level:
437 self.f.write('setvar ')
438 elif defined_locally:
439 self.f.write('set ')
440 #self.f.write('[local mutated]')
441 else:
442 # We're in a function, but it's not defined locally, so we must be
443 # mutating a global.
444 self.f.write('setvar ')
445
446 # foo=bar spam=eggs -> foo = 'bar', spam = 'eggs'
447 n = len(node.pairs)
448 for i, pair in enumerate(node.pairs):
449 lhs = pair.lhs
450 UP_lhs = lhs
451 with tagswitch(lhs) as case:
452 if case(sh_lhs_e.Name):
453 lhs = cast(sh_lhs.Name, UP_lhs)
454
455 self.cursor.PrintUntil(pair.left)
456 # Assume skipping over one Lit_VarLike token
457 self.cursor.SkipPast(pair.left)
458
459 # Replace name. I guess it's Lit_Chars.
460 self.f.write(lhs.name)
461 self.f.write(' = ')
462
463 # TODO: This should be translated from Empty.
464 if pair.rhs.tag() == rhs_word_e.Empty:
465 self.f.write("''") # local i -> var i = ''
466 else:
467 self.DoRhsWord(pair.rhs, local_symbols)
468
469 elif case(sh_lhs_e.UnparsedIndex):
470 # --one-pass-parse gives us this node, instead of IndexedName
471 pass
472
473 else:
474 raise AssertionError(pair.lhs.__class__.__name__)
475
476 if i != n - 1:
477 self.f.write(',')
478
479 def _DoSimple(self, node, local_symbols):
480 # type: (command.Simple, Dict[str, bool]) -> None
481
482 # How to preserve spaces between words? Do you want to do it?
483 # Well you need to test this:
484 #
485 # echo foo \
486 # bar
487
488 if len(node.more_env):
489 # We only need to transform the right side, not left side.
490 for pair in node.more_env:
491 self.DoRhsWord(pair.val, local_symbols)
492
493 if len(node.words):
494 first_word = node.words[0]
495 ok, val, quoted = word_.StaticEval(first_word)
496 word0_tok = location.LeftTokenForWord(first_word)
497 if ok and not quoted:
498 if val == '[' and len(node.words) >= 3:
499 word2 = node.words[-2]
500 last_word = node.words[-1]
501
502 # Check if last word is ]
503 ok, val, quoted = word_.StaticEval(last_word)
504 if ok and not quoted and val == ']':
505 # Replace [ with 'test'
506 self.cursor.PrintUntil(word0_tok)
507 self.cursor.SkipPast(word0_tok)
508 self.f.write('test')
509
510 for w in node.words[1:-1]:
511 self.DoWordInCommand(w, local_symbols)
512
513 # Now omit ]
514 tok2 = location.RightTokenForWord(word2)
515 rbrack_tok = location.LeftTokenForWord(last_word)
516
517 # Skip the space token before ]
518 self.cursor.PrintIncluding(tok2)
519 # ] takes one spid
520 self.cursor.SkipPast(rbrack_tok)
521 return
522 else:
523 raise RuntimeError('Got [ without ]')
524
525 elif val == '.':
526 self.cursor.PrintUntil(word0_tok)
527 self.cursor.SkipPast(word0_tok)
528 self.f.write('source')
529 return
530
531 for w in node.words:
532 self.DoWordInCommand(w, local_symbols)
533
534 # It would be nice to convert here docs to multi-line strings
535 for r in node.redirects:
536 self.DoRedirect(r, local_symbols)
537
538 # TODO: Print the terminator. Could be \n or ;
539 # Need to print env like PYTHONPATH = 'foo' && ls
540 # Need to print redirects:
541 # < > are the same. << is here string, and >> is assignment.
542 # append is >+
543
544 # TODO: static_eval of simple command
545 # - [ -> "test". Eliminate trailing ].
546 # - . -> source, etc.
547
548 def DoCommand(self, node, local_symbols, at_top_level=False):
549 # type: (command_t, Dict[str, bool], bool) -> None
550
551 UP_node = node
552
553 with tagswitch(node) as case:
554 if case(command_e.CommandList):
555 node = cast(command.CommandList, UP_node)
556
557 # TODO: How to distinguish between echo hi; echo bye; and on
558 # separate lines
559 for child in node.children:
560 self.DoCommand(child,
561 local_symbols,
562 at_top_level=at_top_level)
563
564 elif case(command_e.Simple):
565 node = cast(command.Simple, UP_node)
566
567 self._DoSimple(node, local_symbols)
568
569 elif case(command_e.ShAssignment):
570 node = cast(command.ShAssignment, UP_node)
571
572 self.DoShAssignment(node, at_top_level, local_symbols)
573
574 elif case(command_e.Pipeline):
575 node = cast(command.Pipeline, UP_node)
576
577 for child in node.children:
578 self.DoCommand(child, local_symbols)
579
580 elif case(command_e.AndOr):
581 node = cast(command.AndOr, UP_node)
582
583 for child in node.children:
584 self.DoCommand(child, local_symbols)
585
586 elif case(command_e.Sentence):
587 node = cast(command.Sentence, UP_node)
588
589 # 'ls &' to 'fork ls'
590 # Keep ; the same.
591 self.DoCommand(node.child, local_symbols)
592
593 # This has to be different in the function case.
594 elif case(command_e.BraceGroup):
595 node = cast(BraceGroup, UP_node)
596
597 # { echo hi; } -> do { echo hi }
598 # For now it might be OK to keep 'do { echo hi; }
599 self.cursor.PrintUntil(node.left)
600 self.cursor.SkipPast(node.left)
601 self.f.write('do {')
602
603 for child in node.children:
604 self.DoCommand(child, local_symbols)
605
606 elif case(command_e.Subshell):
607 node = cast(command.Subshell, UP_node)
608
609 # (echo hi) -> shell echo hi
610 # (echo hi; echo bye) -> shell {echo hi; echo bye}
611
612 self.cursor.PrintUntil(node.left)
613 self.cursor.SkipPast(node.left)
614 self.f.write('shell {')
615
616 self.DoCommand(node.child, local_symbols)
617
618 #self._DebugSpid(right_spid)
619 #self._DebugSpid(right_spid + 1)
620
621 #print('RIGHT SPID', right_spid)
622 self.cursor.PrintUntil(node.right)
623 self.cursor.SkipPast(node.right)
624 self.f.write('}')
625
626 elif case(command_e.ShFunction):
627 node = cast(command.ShFunction, UP_node)
628
629 # TODO: skip name
630 #self.f.write('proc %s' % node.name)
631
632 # New symbol table for every function.
633 new_local_symbols = {} # type: Dict[str, bool]
634
635 # Should be the left most span, including 'function'
636 if node.keyword: # function foo { ...
637 self.cursor.PrintUntil(node.keyword)
638 else: # foo() { ...
639 self.cursor.PrintUntil(node.name_tok)
640
641 self.f.write('proc %s ' % node.name)
642
643 UP_body = node.body
644 with tagswitch(UP_body) as case:
645 if case(command_e.BraceGroup):
646 body = cast(BraceGroup, UP_body)
647 self.cursor.SkipUntil(body.left)
648
649 # Don't add "do" like a standalone brace group. Just use {}.
650 for child in body.children:
651 self.DoCommand(child, new_local_symbols)
652 else:
653 # very rare cases like f() ( subshell )
654 pass
655
656 elif case(command_e.DoGroup):
657 node = cast(command.DoGroup, UP_node)
658
659 self.cursor.PrintUntil(node.left)
660 self.cursor.SkipPast(node.left)
661 self.f.write('{')
662
663 for child in node.children:
664 self.DoCommand(child, local_symbols)
665
666 self.cursor.PrintUntil(node.right)
667 self.cursor.SkipPast(node.right)
668 self.f.write('}')
669
670 elif case(command_e.ForEach):
671 node = cast(command.ForEach, UP_node)
672
673 # Need to preserve spaces between words, because there can be line
674 # wrapping.
675 # for x in a b c \
676 # d e f; do
677
678 UP_iterable = node.iterable
679 with tagswitch(node.iterable) as case:
680 if case(for_iter_e.Args):
681 self.f.write('for %s in @ARGV ' % node.iter_names[0])
682
683 # note: command_t doesn't have .spids
684 body_tok = location.TokenForCommand(node.body)
685 self.cursor.SkipUntil(body_tok)
686
687 elif case(for_iter_e.Words):
688 pass
689
690 elif case(for_iter_e.YshExpr):
691 pass
692
693 if node.semi_tok is not None:
694 self.cursor.PrintUntil(node.semi_tok)
695 self.cursor.SkipPast(node.semi_tok)
696
697 self.DoCommand(node.body, local_symbols)
698
699 elif case(command_e.WhileUntil):
700 node = cast(command.WhileUntil, UP_node)
701
702 # Skip 'until', and replace it with 'while not'
703 if node.keyword.id == Id.KW_Until:
704 self.cursor.PrintUntil(node.keyword)
705 self.cursor.SkipPast(node.keyword)
706 self.f.write('while !')
707
708 if node.cond.tag() == condition_e.Shell:
709 commands = cast(condition.Shell, node.cond).commands
710 # Skip the semi-colon in the condition, which is usually a Sentence
711 if len(commands) == 1 and commands[0].tag(
712 ) == command_e.Sentence:
713 sentence = cast(command.Sentence, commands[0])
714 self.DoCommand(sentence.child, local_symbols)
715 self.cursor.SkipPast(sentence.terminator)
716
717 self.DoCommand(node.body, local_symbols)
718
719 elif case(command_e.If):
720 node = cast(command.If, UP_node)
721
722 # if foo; then -> if foo {
723 # elif foo; then -> } elif foo {
724 for i, arm in enumerate(node.arms):
725 elif_tok = arm.keyword
726 then_tok = arm.then_tok
727
728 if i != 0: # 'if' not 'elif' on the first arm
729 self.cursor.PrintUntil(elif_tok)
730 self.f.write('} ')
731
732 cond = arm.cond
733 if cond.tag() == condition_e.Shell:
734 commands = cast(condition.Shell, cond).commands
735 if (len(commands) == 1 and
736 commands[0].tag() == command_e.Sentence):
737 sentence = cast(command.Sentence, commands[0])
738 self.DoCommand(sentence, local_symbols)
739
740 # Remove semi-colon
741 self.cursor.PrintUntil(sentence.terminator)
742 self.cursor.SkipPast(sentence.terminator)
743 else:
744 for child in commands:
745 self.DoCommand(child, local_symbols)
746
747 self.cursor.PrintUntil(then_tok)
748 self.cursor.SkipPast(then_tok)
749 self.f.write('{')
750
751 for child in arm.action:
752 self.DoCommand(child, local_symbols)
753
754 # else -> } else {
755 if len(node.else_action):
756 self.cursor.PrintUntil(node.else_kw)
757 self.f.write('} ')
758 self.cursor.PrintIncluding(node.else_kw)
759 self.f.write(' {')
760
761 for child in node.else_action:
762 self.DoCommand(child, local_symbols)
763
764 # fi -> }
765 self.cursor.PrintUntil(node.fi_kw)
766 self.cursor.SkipPast(node.fi_kw)
767 self.f.write('}')
768
769 elif case(command_e.Case):
770 node = cast(command.Case, UP_node)
771
772 to_match = None # type: word_t
773 with tagswitch(node.to_match) as case:
774 if case(case_arg_e.YshExpr):
775 return
776 elif case(case_arg_e.Word):
777 to_match = cast(case_arg.Word, node.to_match).w
778 else:
779 raise AssertionError()
780
781 self.cursor.PrintIncluding(node.case_kw)
782
783 # Figure out the variable name, so we can translate
784 # - $var to (var)
785 # - "$var" to (var)
786 var_part = None # type: SimpleVarSub
787 with tagswitch(to_match) as case:
788 if case(word_e.Compound):
789 w = cast(CompoundWord, to_match)
790 part0 = w.parts[0]
791
792 with tagswitch(part0) as case2:
793 if case2(word_part_e.SimpleVarSub):
794 var_part = cast(SimpleVarSub, part0)
795
796 elif case2(word_part_e.DoubleQuoted):
797 dq_part = cast(DoubleQuoted, part0)
798 if len(dq_part.parts) == 1:
799 dq_part0 = dq_part.parts[0]
800
801 # Nesting is annoying -- it would be nice to use pattern
802 # matching, but mycpp won't like it.
803 # TODO: extract into a common function
804 with tagswitch(dq_part0) as case3:
805 if case3(word_part_e.SimpleVarSub):
806 var_part = cast(
807 SimpleVarSub, dq_part0)
808 #log("VAR PART %s", var_part)
809
810 if var_part:
811 self.f.write(' (')
812 self.f.write(lexer.LazyStr(var_part.tok))
813 self.f.write(') ')
814
815 self.cursor.SkipPast(node.arms_start) # Skip past 'in'
816 self.f.write('{')
817
818 missing_last_dsemi = False
819
820 for case_arm in node.arms:
821 # Replace ) with {
822 self.cursor.PrintUntil(case_arm.middle)
823 self.f.write(' {')
824 self.cursor.SkipPast(case_arm.middle)
825
826 for child in case_arm.action:
827 self.DoCommand(child, local_symbols)
828
829 if case_arm.right:
830 # Change ;; to }
831 self.cursor.PrintUntil(case_arm.right)
832 self.f.write('}')
833 self.cursor.SkipPast(case_arm.right)
834 else:
835 # valid: case $x in pat) echo hi ; esac
836 missing_last_dsemi = True
837
838 self.cursor.PrintUntil(node.arms_end) # 'esac' or }
839
840 if missing_last_dsemi: # Print } for missing ;;
841 self.f.write('}\n')
842
843 self.cursor.SkipPast(node.arms_end) # 'esac' or }
844
845 self.f.write('}') # in place of 'esac'
846
847 elif case(command_e.TimeBlock):
848 node = cast(command.TimeBlock, UP_node)
849
850 self.DoCommand(node.pipeline, local_symbols)
851
852 elif case(command_e.DParen):
853 node = cast(command.DParen, UP_node)
854 # TODO: arith expressions can words with command subs
855 pass
856
857 elif case(command_e.DBracket):
858 node = cast(command.DBracket, UP_node)
859
860 # TODO: bool_expr_t can have words with command subs
861 pass
862
863 else:
864 pass
865 #log('Command not handled: %s', node)
866 #raise AssertionError(node.__class__.__name__)
867
868 def DoRhsWord(self, node, local_symbols):
869 # type: (rhs_word_t, Dict[str, bool]) -> None
870 """For the RHS of assignments.
871
872 TODO: for complex cases of word joining:
873 local a=unquoted'single'"double"'"'
874
875 We can try to handle it:
876 var a = y"unquotedsingledouble\""
877
878 Or simply abort and LEAVE IT ALONE. We should only translate things we
879 recognize.
880 """
881 UP_node = node
882 with tagswitch(node) as case:
883 if case(rhs_word_e.Empty):
884 self.f.write("''")
885
886 elif case(rhs_word_e.Compound):
887 node = cast(CompoundWord, UP_node)
888
889 # TODO: This is wrong!
890 style = _GetRhsStyle(node)
891 if style == word_style_e.SQ:
892 self.f.write("'")
893 self.DoWordInCommand(node, local_symbols)
894 self.f.write("'")
895 elif style == word_style_e.DQ:
896 self.f.write('"')
897 self.DoWordInCommand(node, local_symbols)
898 self.f.write('"')
899 # TODO: Put these back
900 #elif style == word_style_e.Expr:
901 # pass
902 #elif style == word_style_e.Unquoted:
903 # pass
904 else:
905 # "${foo:-default}" -> foo or 'default'
906 # ${foo:-default} -> @split(foo or 'default')
907 # @(foo or 'default') -- implicit split.
908
909 if word_.IsVarSub(node): # ${1} or "$1"
910 # Do it in expression mode
911 pass
912 # NOTE: ArithSub with $(1 +2 ) is different than 1 + 2 because of
913 # conversion to string.
914
915 # For now, just stub it out
916 self.DoWordInCommand(node, local_symbols)
917
918 def DoWordInCommand(self, node, local_symbols):
919 # type: (word_t, Dict[str, bool]) -> None
920 """E.g. remove unquoted.
921
922 echo "$x" -> echo $x
923 """
924 UP_node = node
925
926 with tagswitch(node) as case:
927 if case(word_e.Compound):
928 node = cast(CompoundWord, UP_node)
929
930 # UNQUOTE simple var subs
931
932 # Special case for "$@".
933 # TODO:
934 # "$foo" -> $foo
935 # "${foo}" -> $foo
936
937 if (len(node.parts) == 1 and
938 node.parts[0].tag() == word_part_e.DoubleQuoted):
939 dq_part = cast(DoubleQuoted, node.parts[0])
940
941 # NOTE: In double quoted case, this is the begin and end quote.
942 # Do we need a HereDoc part?
943
944 if len(dq_part.parts) == 1:
945 part0 = dq_part.parts[0]
946 if part0.tag() == word_part_e.SimpleVarSub:
947 vsub_part = cast(SimpleVarSub, dq_part.parts[0])
948 if vsub_part.tok.id == Id.VSub_At:
949 self.cursor.PrintUntil(dq_part.left)
950 self.cursor.SkipPast(
951 dq_part.right) # " then $@ then "
952 self.f.write('@ARGV')
953 return # Done replacing
954
955 # "$1" -> $1, "$foo" -> $foo
956 if vsub_part.tok.id in (Id.VSub_Number,
957 Id.VSub_DollarName):
958 self.cursor.PrintUntil(dq_part.left)
959 self.cursor.SkipPast(dq_part.right)
960 self.f.write(lexer.TokenVal(vsub_part.tok))
961 return
962
963 # Single arith sub, command sub, etc.
964 # On the other hand, an unquoted one needs to turn into
965 #
966 # $(echo one two) -> @[echo one two]
967 # `echo one two` -> @[echo one two]
968 #
969 # ${var:-'the default'} -> @$(var or 'the default')
970 #
971 # $((1 + 2)) -> $(1 + 2) -- this is OK unquoted
972
973 elif part0.tag() == word_part_e.BracedVarSub:
974 # Skip over quote
975 self.cursor.PrintUntil(dq_part.left)
976 self.cursor.SkipPast(dq_part.left)
977 self.DoWordPart(part0, local_symbols)
978 self.cursor.SkipPast(dq_part.right)
979 return
980
981 elif part0.tag() == word_part_e.CommandSub:
982 self.cursor.PrintUntil(dq_part.left)
983 self.cursor.SkipPast(dq_part.left)
984 self.DoWordPart(part0, local_symbols)
985 self.cursor.SkipPast(dq_part.right)
986 return
987
988 # TODO: 'foo'"bar" should be "foobar", etc.
989 # If any part is double quoted, you can always double quote the whole
990 # thing?
991 for part in node.parts:
992 self.DoWordPart(part, local_symbols)
993
994 elif case(word_e.BracedTree):
995 # Not doing anything now
996 pass
997
998 else:
999 raise AssertionError(node.__class__.__name__)
1000
1001 def DoWordPart(self, node, local_symbols, quoted=False):
1002 # type: (word_part_t, Dict[str, bool], bool) -> None
1003
1004 left_tok = location.LeftTokenForWordPart(node)
1005 if left_tok:
1006 self.cursor.PrintUntil(left_tok)
1007
1008 UP_node = node
1009
1010 with tagswitch(node) as case:
1011 if case(word_part_e.ShArrayLiteral, word_part_e.BashAssocLiteral,
1012 word_part_e.TildeSub, word_part_e.ExtGlob):
1013 pass
1014
1015 elif case(word_part_e.EscapedLiteral):
1016 node = cast(word_part.EscapedLiteral, UP_node)
1017 if quoted:
1018 pass
1019 else:
1020 # If unquoted \e, it should quoted instead. ' ' vs. \<invisible space>
1021 # Hm is this necessary though? I think the only motivation is changing
1022 # \{ and \( for macros. And ' ' to be readable/visible.
1023 t = node.token
1024 val = lexer.TokenSliceLeft(t, 1)
1025 assert len(val) == 1, val
1026 if val != '\n':
1027 self.cursor.PrintUntil(t)
1028 self.cursor.SkipPast(t)
1029 self.f.write("'%s'" % val)
1030
1031 elif case(word_part_e.Literal):
1032 node = cast(Token, UP_node)
1033 self.cursor.PrintIncluding(node)
1034
1035 elif case(word_part_e.SingleQuoted):
1036 node = cast(SingleQuoted, UP_node)
1037
1038 # TODO:
1039 # '\n' is '\\n'
1040 # $'\n' is '\n'
1041 # TODO: Should print until right_spid
1042 # left_spid, right_spid = node.spids
1043 self.cursor.PrintUntil(node.right)
1044
1045 elif case(word_part_e.DoubleQuoted):
1046 node = cast(DoubleQuoted, UP_node)
1047 for part in node.parts:
1048 self.DoWordPart(part, local_symbols, quoted=True)
1049
1050 elif case(word_part_e.SimpleVarSub):
1051 node = cast(SimpleVarSub, UP_node)
1052
1053 op_id = node.tok.id
1054
1055 if op_id == Id.VSub_DollarName:
1056 self.cursor.PrintIncluding(node.tok)
1057
1058 elif op_id == Id.VSub_Number:
1059 self.cursor.PrintIncluding(node.tok)
1060
1061 elif op_id == Id.VSub_At: # $@ -- handled quoted case above
1062 self.f.write('$[join(ARGV)]')
1063 self.cursor.SkipPast(node.tok)
1064
1065 elif op_id == Id.VSub_Star: # $*
1066 # PEDANTIC: Depends if quoted or unquoted
1067 self.f.write('$[join(ARGV)]')
1068 self.cursor.SkipPast(node.tok)
1069
1070 elif op_id == Id.VSub_Pound: # $#
1071 # len(ARGV) ?
1072 self.f.write('$Argc')
1073 self.cursor.SkipPast(node.tok)
1074
1075 else:
1076 pass
1077
1078 elif case(word_part_e.BracedVarSub):
1079 node = cast(BracedVarSub, UP_node)
1080
1081 # NOTE: Why do we need this but we don't need it in command sub?
1082 self.cursor.PrintUntil(node.left)
1083
1084 if node.bracket_op:
1085 # a[1]
1086 # These two change the sigil! ${a[@]} is now @a!
1087 # a[@]
1088 # a[*]
1089 pass
1090
1091 if node.prefix_op:
1092 # len()
1093 pass
1094 if node.suffix_op:
1095 pass
1096
1097 op_id = node.token.id
1098 if op_id == Id.VSub_QMark:
1099 self.cursor.PrintIncluding(node.token)
1100
1101 self.cursor.PrintIncluding(node.right)
1102
1103 elif case(word_part_e.CommandSub):
1104 node = cast(CommandSub, UP_node)
1105
1106 if node.left_token.id == Id.Left_Backtick:
1107 self.cursor.PrintUntil(node.left_token)
1108 self.f.write('$(')
1109 self.cursor.SkipPast(node.left_token)
1110
1111 self.DoCommand(node.child, local_symbols)
1112
1113 # Skip over right `
1114 self.cursor.SkipPast(node.right)
1115 self.f.write(')')
1116
1117 else:
1118 self.cursor.PrintIncluding(node.right)
1119
1120 else:
1121 pass