1 | #!/usr/bin/env python2
|
2 | """
|
3 | builtin/io_ysh.py - YSH builtins that perform I/O
|
4 | """
|
5 | from __future__ import print_function
|
6 |
|
7 | from _devbuild.gen import arg_types
|
8 | from _devbuild.gen.runtime_asdl import cmd_value
|
9 | from _devbuild.gen.syntax_asdl import command_e, BraceGroup
|
10 | from _devbuild.gen.value_asdl import value, value_e
|
11 | from asdl import format as fmt
|
12 | from core import error
|
13 | from core.error import e_usage
|
14 | from core import state
|
15 | from display import ui
|
16 | from core import vm
|
17 | from data_lang import j8
|
18 | from frontend import flag_util
|
19 | from frontend import match
|
20 | from frontend import typed_args
|
21 | from mycpp import mylib
|
22 | from mycpp.mylib import log, iteritems
|
23 |
|
24 | from typing import TYPE_CHECKING, cast
|
25 | if TYPE_CHECKING:
|
26 | from core.alloc import Arena
|
27 | from osh import cmd_eval
|
28 | from ysh import expr_eval
|
29 |
|
30 | _ = log
|
31 |
|
32 |
|
33 | class _Builtin(vm._Builtin):
|
34 |
|
35 | def __init__(self, mem, errfmt):
|
36 | # type: (state.Mem, ui.ErrorFormatter) -> None
|
37 | self.mem = mem
|
38 | self.errfmt = errfmt
|
39 |
|
40 |
|
41 | class Pp(_Builtin):
|
42 | """Given a list of variable names, print their values.
|
43 |
|
44 | 'pp cell a' is a lot easier to type than 'argv.py "${a[@]}"'.
|
45 | """
|
46 |
|
47 | def __init__(
|
48 | self,
|
49 | expr_ev, # type: expr_eval.ExprEvaluator
|
50 | mem, # type: state.Mem
|
51 | errfmt, # type: ui.ErrorFormatter
|
52 | procs, # type: state.Procs
|
53 | arena, # type: Arena
|
54 | ):
|
55 | # type: (...) -> None
|
56 | _Builtin.__init__(self, mem, errfmt)
|
57 | self.expr_ev = expr_ev
|
58 | self.procs = procs
|
59 | self.arena = arena
|
60 | self.stdout_ = mylib.Stdout()
|
61 |
|
62 | def _PrettyPrint(self, cmd_val):
|
63 | # type: (cmd_value.Argv) -> int
|
64 | rd = typed_args.ReaderForProc(cmd_val)
|
65 | val = rd.PosValue()
|
66 | rd.Done()
|
67 |
|
68 | blame_tok = rd.LeftParenToken()
|
69 |
|
70 | # Show it with location
|
71 | # It looks like
|
72 | # pp (42)
|
73 | # ^
|
74 | # [ stdin ]:5: (Int) 42
|
75 | # We could also print with ! or -^-
|
76 |
|
77 | self.stdout_.write('\n')
|
78 | excerpt, prefix = ui.CodeExcerptAndPrefix(blame_tok)
|
79 | self.stdout_.write(excerpt)
|
80 | ui.PrettyPrintValue(prefix, val, self.stdout_)
|
81 |
|
82 | return 0
|
83 |
|
84 | def Run(self, cmd_val):
|
85 | # type: (cmd_value.Argv) -> int
|
86 | arg, arg_r = flag_util.ParseCmdVal('pp',
|
87 | cmd_val,
|
88 | accept_typed_args=True)
|
89 |
|
90 | action, action_loc = arg_r.Peek2()
|
91 |
|
92 | # Special cases
|
93 | # pp (x) quotes its code location, can also be pp [x]
|
94 | if action is None:
|
95 | return self._PrettyPrint(cmd_val)
|
96 |
|
97 | arg_r.Next()
|
98 |
|
99 | if action == 'value':
|
100 | # pp value (x) prints in the same way that '= x' does
|
101 | rd = typed_args.ReaderForProc(cmd_val)
|
102 | val = rd.PosValue()
|
103 | rd.Done()
|
104 |
|
105 | ui.PrettyPrintValue('', val, self.stdout_)
|
106 | return 0
|
107 |
|
108 | if action == 'asdl_':
|
109 | # TODO: could be pp asdl_ (x, y, z)
|
110 | rd = typed_args.ReaderForProc(cmd_val)
|
111 | val = rd.PosValue()
|
112 | rd.Done()
|
113 |
|
114 | tree = val.PrettyTree(False)
|
115 |
|
116 | # TODO: ASDL should print the IDs. And then they will be
|
117 | # line-wrapped.
|
118 | # The IDs should also be used to detect cycles, and omit values
|
119 | # already printed.
|
120 | #id_str = vm.ValueIdString(val)
|
121 | #f.write(' <%s%s>\n' % (ysh_type, id_str))
|
122 |
|
123 | max_width = ui._GetMaxWidth()
|
124 | fmt.HNodePrettyPrint(tree, self.stdout_, max_width=max_width)
|
125 | #self.stdout_.write('\n')
|
126 |
|
127 | return 0
|
128 |
|
129 | if action == 'test_': # Print format for spec tests
|
130 | # TODO: could be pp test_ (x, y, z)
|
131 | rd = typed_args.ReaderForProc(cmd_val)
|
132 | val = rd.PosValue()
|
133 | rd.Done()
|
134 |
|
135 | if ui.TypeNotPrinted(val):
|
136 | ysh_type = ui.ValType(val)
|
137 | self.stdout_.write('(%s) ' % ysh_type)
|
138 |
|
139 | j8.PrintLine(val, self.stdout_)
|
140 |
|
141 | return 0
|
142 |
|
143 | if action == 'cell_': # Format may change
|
144 | argv, locs = arg_r.Rest2()
|
145 |
|
146 | status = 0
|
147 | for i, name in enumerate(argv):
|
148 |
|
149 | if not match.IsValidVarName(name):
|
150 | raise error.Usage('got invalid variable name %r' % name,
|
151 | locs[i])
|
152 |
|
153 | cell = self.mem.GetCell(name)
|
154 | if cell is None:
|
155 | self.errfmt.Print_("Couldn't find a variable named %r" %
|
156 | name,
|
157 | blame_loc=locs[i])
|
158 | status = 1
|
159 | else:
|
160 | self.stdout_.write('%s = ' % name)
|
161 | fmt.HNodePrettyPrint(cell.PrettyTree(False), self.stdout_)
|
162 | return status
|
163 |
|
164 | if action == 'stacks_': # Format may change
|
165 | if mylib.PYTHON:
|
166 | var_stack, argv_stack, unused = self.mem.Dump()
|
167 | print(var_stack)
|
168 | print('===')
|
169 | print(argv_stack)
|
170 | if 0:
|
171 | var_stack = self.mem.var_stack
|
172 | for i, frame in enumerate(var_stack):
|
173 | print('=== Frame %d' % i)
|
174 | for name, cell in iteritems(frame):
|
175 | print('%s = %s' % (name, cell))
|
176 |
|
177 | return 0
|
178 |
|
179 | if action == 'frame_vars_': # Print names in current frame, for testing
|
180 | top = self.mem.var_stack[-1]
|
181 | print(' [frame_vars_] %s' % ' '.join(top.keys()))
|
182 | return 0
|
183 |
|
184 | if action == 'gc-stats_':
|
185 | print('TODO')
|
186 | return 0
|
187 |
|
188 | if action == 'proc':
|
189 | names, locs = arg_r.Rest2()
|
190 | if len(names):
|
191 | for i, name in enumerate(names):
|
192 | node, _ = self.procs.GetInvokable(name)
|
193 | if node is None:
|
194 | self.errfmt.Print_('Invalid proc %r' % name,
|
195 | blame_loc=locs[i])
|
196 | return 1
|
197 | else:
|
198 | names = self.procs.InvokableNames()
|
199 |
|
200 | # TSV8 header
|
201 | print('proc_name\tdoc_comment')
|
202 | for name in names:
|
203 | proc_val, _ = self.procs.GetInvokable(name) # must exist
|
204 | if proc_val.tag() != value_e.Proc:
|
205 | continue # can't be value.BuiltinProc
|
206 | user_proc = cast(value.Proc, proc_val)
|
207 |
|
208 | body = user_proc.body
|
209 |
|
210 | # TODO: not just command.ShFunction, but command.Proc!
|
211 | doc = ''
|
212 | if body.tag() == command_e.BraceGroup:
|
213 | bgroup = cast(BraceGroup, body)
|
214 | if bgroup.doc_token:
|
215 | token = bgroup.doc_token
|
216 | # 1 to remove leading space
|
217 | doc = token.line.content[token.col + 1:token.col +
|
218 | token.length]
|
219 |
|
220 | # Note: these should be attributes on value.Proc
|
221 | buf = mylib.BufWriter()
|
222 | j8.EncodeString(name, buf, unquoted_ok=True)
|
223 | buf.write('\t')
|
224 | j8.EncodeString(doc, buf, unquoted_ok=True)
|
225 | print(buf.getvalue())
|
226 |
|
227 | return 0
|
228 |
|
229 | e_usage('got invalid action %r' % action, action_loc)
|
230 | #return status
|
231 |
|
232 |
|
233 | class Write(_Builtin):
|
234 | """
|
235 | write -- @strs
|
236 | write --sep ' ' --end '' -- @strs
|
237 | write -n -- @
|
238 | write --j8 -- @strs # argv serialization
|
239 | write --j8 --sep $'\t' -- @strs # this is like TSV8
|
240 | """
|
241 |
|
242 | def __init__(self, mem, errfmt):
|
243 | # type: (state.Mem, ui.ErrorFormatter) -> None
|
244 | _Builtin.__init__(self, mem, errfmt)
|
245 | self.stdout_ = mylib.Stdout()
|
246 |
|
247 | def Run(self, cmd_val):
|
248 | # type: (cmd_value.Argv) -> int
|
249 | attrs, arg_r = flag_util.ParseCmdVal('write', cmd_val)
|
250 | arg = arg_types.write(attrs.attrs)
|
251 | #print(arg)
|
252 |
|
253 | i = 0
|
254 | while not arg_r.AtEnd():
|
255 | if i != 0:
|
256 | self.stdout_.write(arg.sep)
|
257 | s = arg_r.Peek()
|
258 |
|
259 | if arg.json:
|
260 | s = j8.MaybeEncodeJsonString(s)
|
261 |
|
262 | elif arg.j8:
|
263 | s = j8.MaybeEncodeString(s)
|
264 |
|
265 | self.stdout_.write(s)
|
266 |
|
267 | arg_r.Next()
|
268 | i += 1
|
269 |
|
270 | if arg.n:
|
271 | pass
|
272 | elif len(arg.end):
|
273 | self.stdout_.write(arg.end)
|
274 |
|
275 | return 0
|
276 |
|
277 |
|
278 | class RunBlock(vm._Builtin):
|
279 | """Used for 'redir' builtin
|
280 |
|
281 | It's used solely for its redirects.
|
282 | redir >out.txt { echo hi }
|
283 | """
|
284 |
|
285 | def __init__(self, mem, cmd_ev):
|
286 | # type: (state.Mem, cmd_eval.CommandEvaluator) -> None
|
287 | self.mem = mem
|
288 | self.cmd_ev = cmd_ev # To run blocks
|
289 |
|
290 | def Run(self, cmd_val):
|
291 | # type: (cmd_value.Argv) -> int
|
292 | _, arg_r = flag_util.ParseCmdVal('redir',
|
293 | cmd_val,
|
294 | accept_typed_args=True)
|
295 |
|
296 | cmd_frag = typed_args.RequiredBlockAsFrag(cmd_val)
|
297 | unused = self.cmd_ev.EvalCommandFrag(cmd_frag)
|
298 | return 0
|