| 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.value_asdl import value, value_e
|
| 10 | from asdl import format as fmt
|
| 11 | from builtin import method_other
|
| 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 | # TODO: should be #.qtt8
|
| 202 | print('proc_name\tdoc_comment')
|
| 203 | for name in names:
|
| 204 | proc_val, _ = self.procs.GetInvokable(name) # must exist
|
| 205 | if proc_val.tag() != value_e.Proc:
|
| 206 | continue # can't be value.BuiltinProc
|
| 207 | user_proc = cast(value.Proc, proc_val)
|
| 208 |
|
| 209 | doc = method_other.GetDocComment(user_proc.body)
|
| 210 | if doc is None:
|
| 211 | doc = ''
|
| 212 |
|
| 213 | # Note: these should be attributes on value.Proc
|
| 214 | buf = mylib.BufWriter()
|
| 215 | j8.EncodeString(name, buf, unquoted_ok=True)
|
| 216 | buf.write('\t')
|
| 217 | j8.EncodeString(doc, buf, unquoted_ok=True)
|
| 218 | print(buf.getvalue())
|
| 219 |
|
| 220 | return 0
|
| 221 |
|
| 222 | e_usage('got invalid action %r' % action, action_loc)
|
| 223 | #return status
|
| 224 |
|
| 225 |
|
| 226 | class Write(_Builtin):
|
| 227 | """
|
| 228 | write -- @strs
|
| 229 | write --sep ' ' --end '' -- @strs
|
| 230 | write -n -- @
|
| 231 | write --j8 -- @strs # argv serialization
|
| 232 | write --j8 --sep $'\t' -- @strs # this is like TSV8
|
| 233 | """
|
| 234 |
|
| 235 | def __init__(self, mem, errfmt):
|
| 236 | # type: (state.Mem, ui.ErrorFormatter) -> None
|
| 237 | _Builtin.__init__(self, mem, errfmt)
|
| 238 | self.stdout_ = mylib.Stdout()
|
| 239 |
|
| 240 | def Run(self, cmd_val):
|
| 241 | # type: (cmd_value.Argv) -> int
|
| 242 | attrs, arg_r = flag_util.ParseCmdVal('write', cmd_val)
|
| 243 | arg = arg_types.write(attrs.attrs)
|
| 244 | #print(arg)
|
| 245 |
|
| 246 | i = 0
|
| 247 | while not arg_r.AtEnd():
|
| 248 | if i != 0:
|
| 249 | self.stdout_.write(arg.sep)
|
| 250 | s = arg_r.Peek()
|
| 251 |
|
| 252 | if arg.json:
|
| 253 | s = j8.MaybeEncodeJsonString(s)
|
| 254 |
|
| 255 | elif arg.j8:
|
| 256 | s = j8.MaybeEncodeString(s)
|
| 257 |
|
| 258 | self.stdout_.write(s)
|
| 259 |
|
| 260 | arg_r.Next()
|
| 261 | i += 1
|
| 262 |
|
| 263 | if arg.n:
|
| 264 | pass
|
| 265 | elif len(arg.end):
|
| 266 | self.stdout_.write(arg.end)
|
| 267 |
|
| 268 | return 0
|
| 269 |
|
| 270 |
|
| 271 | class RunBlock(vm._Builtin):
|
| 272 | """Used for 'redir' builtin
|
| 273 |
|
| 274 | It's used solely for its redirects.
|
| 275 | redir >out.txt { echo hi }
|
| 276 | """
|
| 277 |
|
| 278 | def __init__(self, mem, cmd_ev):
|
| 279 | # type: (state.Mem, cmd_eval.CommandEvaluator) -> None
|
| 280 | self.mem = mem
|
| 281 | self.cmd_ev = cmd_ev # To run blocks
|
| 282 |
|
| 283 | def Run(self, cmd_val):
|
| 284 | # type: (cmd_value.Argv) -> int
|
| 285 | _, arg_r = flag_util.ParseCmdVal('redir',
|
| 286 | cmd_val,
|
| 287 | accept_typed_args=True)
|
| 288 |
|
| 289 | cmd_frag = typed_args.RequiredBlockAsFrag(cmd_val)
|
| 290 | unused = self.cmd_ev.EvalCommandFrag(cmd_frag)
|
| 291 | return 0
|