OILS / builtin / io_ysh.py View on Github | oilshell.org

304 lines, 181 significant
1#!/usr/bin/env python2
2"""
3builtin/io_ysh.py - YSH builtins that perform I/O
4"""
5from __future__ import print_function
6
7from _devbuild.gen import arg_types
8from _devbuild.gen.runtime_asdl import cmd_value
9from _devbuild.gen.syntax_asdl import command_e, BraceGroup, loc
10from _devbuild.gen.value_asdl import value, value_e, value_t
11from asdl import format as fmt
12from core import error
13from core.error import e_usage
14from core import state
15from display import ui
16from core import vm
17from data_lang import j8
18from frontend import flag_util
19from frontend import match
20from frontend import typed_args
21from mycpp import mylib
22from mycpp.mylib import tagswitch, log
23
24from typing import TYPE_CHECKING, cast
25if 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
33class _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
41class 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 # It might be nice to add a string too, like
71 # pp 'my annotation' (actual)
72 # But the var name should meaningful in most cases
73
74 UP_val = val
75 result = None # type: value_t
76 with tagswitch(val) as case:
77 if case(value_e.Expr): # Destructured assert [true === f()]
78 val = cast(value.Expr, UP_val)
79
80 # In this case, we could get the unevaluated code string and
81 # print it. Although quoting the line seems enough.
82 result = self.expr_ev.EvalExpr(val.e, blame_tok)
83 else:
84 result = val
85
86 # Show it with location
87 self.stdout_.write('\n')
88 excerpt, prefix = ui.CodeExcerptAndPrefix(blame_tok)
89 self.stdout_.write(excerpt)
90 ui.PrettyPrintValue(prefix, result, self.stdout_)
91
92 return 0
93
94 def Run(self, cmd_val):
95 # type: (cmd_value.Argv) -> int
96 arg, arg_r = flag_util.ParseCmdVal('pp',
97 cmd_val,
98 accept_typed_args=True)
99
100 action, action_loc = arg_r.Peek2()
101
102 # Special cases
103 # pp (x) quotes its code location
104 # pp [x] also evaluates
105 if action is None:
106 return self._PrettyPrint(cmd_val)
107
108 arg_r.Next()
109
110 if action == 'value':
111 # pp value (x) prints in the same way that '= x' does
112 rd = typed_args.ReaderForProc(cmd_val)
113 val = rd.PosValue()
114 rd.Done()
115
116 ui.PrettyPrintValue('', val, self.stdout_)
117 return 0
118
119 if action == 'asdl':
120 # TODO: could be pp asdl (x, y, z)
121 rd = typed_args.ReaderForProc(cmd_val)
122 val = rd.PosValue()
123 rd.Done()
124
125 tree = val.PrettyTree()
126 #tree = val.AbbreviatedTree() # I used this to test cycle detection
127
128 # TODO: ASDL should print the IDs. And then they will be
129 # line-wrapped.
130 # The IDs should also be used to detect cycles, and omit values
131 # already printed.
132 #id_str = vm.ValueIdString(val)
133 #f.write(' <%s%s>\n' % (ysh_type, id_str))
134
135 pretty_f = fmt.DetectConsoleOutput(self.stdout_)
136 fmt.PrintTree(tree, pretty_f)
137 self.stdout_.write('\n')
138
139 return 0
140
141 if action == 'line':
142 # TODO: could be pp _test
143
144 # Print format for spec tests
145
146 # TODO: could be pp line (x, y, z)
147 rd = typed_args.ReaderForProc(cmd_val)
148 val = rd.PosValue()
149 rd.Done()
150
151 if ui.TypeNotPrinted(val):
152 ysh_type = ui.ValType(val)
153 self.stdout_.write('(%s) ' % ysh_type)
154
155 j8.PrintLine(val, self.stdout_)
156
157 return 0
158
159 if action == 'cell':
160 # should this be pp .cell, and pp .asdl?
161 # or pp _cell pp _asdl?
162 # pp _test is possible too
163 argv, locs = arg_r.Rest2()
164
165 status = 0
166 for i, name in enumerate(argv):
167 if name.startswith(':'):
168 name = name[1:]
169
170 if not match.IsValidVarName(name):
171 raise error.Usage('got invalid variable name %r' % name,
172 locs[i])
173
174 cell = self.mem.GetCell(name)
175 if cell is None:
176 self.errfmt.Print_("Couldn't find a variable named %r" %
177 name,
178 blame_loc=locs[i])
179 status = 1
180 else:
181 self.stdout_.write('%s = ' % name)
182 pretty_f = fmt.DetectConsoleOutput(self.stdout_)
183 fmt.PrintTree(cell.PrettyTree(), pretty_f)
184 self.stdout_.write('\n')
185 return status
186
187 elif action == 'gc-stats':
188 print('TODO')
189 return 0
190
191 elif action == 'proc':
192 names, locs = arg_r.Rest2()
193 if len(names):
194 for i, name in enumerate(names):
195 node = self.procs.Get(name)
196 if node is None:
197 self.errfmt.Print_('Invalid proc %r' % name,
198 blame_loc=locs[i])
199 return 1
200 else:
201 names = self.procs.GetNames()
202
203 # TSV8 header
204 print('proc_name\tdoc_comment')
205 for name in names:
206 proc = self.procs.Get(name) # must exist
207 #log('Proc %s', proc)
208 body = 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
233class 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
278class Fopen(vm._Builtin):
279 """fopen does nothing but run a block.
280
281 It's used solely for its redirects.
282 fopen >out.txt { echo hi }
283
284 It's a subset of eval
285 eval >out.txt { echo hi }
286 """
287
288 def __init__(self, mem, cmd_ev):
289 # type: (state.Mem, cmd_eval.CommandEvaluator) -> None
290 self.mem = mem
291 self.cmd_ev = cmd_ev # To run blocks
292
293 def Run(self, cmd_val):
294 # type: (cmd_value.Argv) -> int
295 _, arg_r = flag_util.ParseCmdVal('fopen',
296 cmd_val,
297 accept_typed_args=True)
298
299 cmd = typed_args.OptionalBlock(cmd_val)
300 if not cmd:
301 raise error.Usage('expected a block', loc.Missing)
302
303 unused = self.cmd_ev.EvalCommand(cmd)
304 return 0