1 | from __future__ import print_function
|
2 |
|
3 | from _devbuild.gen.option_asdl import option_i
|
4 | from _devbuild.gen.id_kind_asdl import Id
|
5 | from _devbuild.gen.runtime_asdl import cmd_value, CommandStatus
|
6 | from _devbuild.gen.syntax_asdl import loc, loc_t, expr, expr_e
|
7 | from _devbuild.gen.value_asdl import value, value_e
|
8 | from core import error
|
9 | from core.error import e_die_status, e_usage
|
10 | from core import executor
|
11 | from core import num
|
12 | from core import state
|
13 | from display import ui
|
14 | from core import vm
|
15 | from frontend import flag_util
|
16 | from frontend import typed_args
|
17 | from mycpp import mops
|
18 | from mycpp import mylib
|
19 | from mycpp.mylib import tagswitch, log
|
20 | from ysh import val_ops
|
21 |
|
22 | _ = log
|
23 |
|
24 | from typing import Any, cast, TYPE_CHECKING
|
25 | if TYPE_CHECKING:
|
26 | from display import ui
|
27 | from osh import cmd_eval
|
28 | from ysh import expr_eval
|
29 |
|
30 |
|
31 | class ctx_Try(object):
|
32 |
|
33 | def __init__(self, mutable_opts):
|
34 | # type: (state.MutableOpts) -> None
|
35 |
|
36 | mutable_opts.Push(option_i.errexit, True)
|
37 | self.mutable_opts = mutable_opts
|
38 |
|
39 | def __enter__(self):
|
40 | # type: () -> None
|
41 | pass
|
42 |
|
43 | def __exit__(self, type, value, traceback):
|
44 | # type: (Any, Any, Any) -> None
|
45 | self.mutable_opts.Pop(option_i.errexit)
|
46 |
|
47 |
|
48 | class Try(vm._Builtin):
|
49 | """Allows explicit handling of errors.
|
50 |
|
51 | Takes command argv, or a block:
|
52 |
|
53 | try ls /bad
|
54 |
|
55 | try {
|
56 | var x = 1 / 0
|
57 |
|
58 | ls | wc -l
|
59 |
|
60 | diff <(sort left.txt) <(sort right.txt)
|
61 | }
|
62 |
|
63 | TODO:
|
64 | - Set _error_str (e.UserErrorString())
|
65 | - Set _error_location
|
66 | - These could be used by a 'raise' builtin? Or 'reraise'
|
67 |
|
68 | try {
|
69 | foo
|
70 | }
|
71 | if (_status !== 0) {
|
72 | echo 'hello'
|
73 | raise # reads _status, _error_str, and _error_location ?
|
74 | }
|
75 | """
|
76 |
|
77 | def __init__(
|
78 | self,
|
79 | mutable_opts, # type: state.MutableOpts
|
80 | mem, # type: state.Mem
|
81 | cmd_ev, # type: cmd_eval.CommandEvaluator
|
82 | shell_ex, # type: vm._Executor
|
83 | errfmt, # type: ui.ErrorFormatter
|
84 | ):
|
85 | # type: (...) -> None
|
86 | self.mutable_opts = mutable_opts
|
87 | self.mem = mem
|
88 | self.shell_ex = shell_ex
|
89 | self.cmd_ev = cmd_ev
|
90 | self.errfmt = errfmt
|
91 |
|
92 | def Run(self, cmd_val):
|
93 | # type: (cmd_value.Argv) -> int
|
94 | _, arg_r = flag_util.ParseCmdVal('try_',
|
95 | cmd_val,
|
96 | accept_typed_args=True)
|
97 |
|
98 | rd = typed_args.ReaderForProc(cmd_val)
|
99 | cmd = rd.RequiredBlockAsFrag()
|
100 | rd.Done()
|
101 |
|
102 | error_dict = None # type: value.Dict
|
103 |
|
104 | status = 0 # success by default
|
105 | try:
|
106 | with ctx_Try(self.mutable_opts):
|
107 | unused = self.cmd_ev.EvalCommandFrag(cmd)
|
108 | except error.Expr as e:
|
109 | status = e.ExitStatus()
|
110 | except error.ErrExit as e:
|
111 | status = e.ExitStatus()
|
112 |
|
113 | except error.Structured as e:
|
114 | #log('*** STRUC %s', e)
|
115 | status = e.ExitStatus()
|
116 | error_dict = e.ToDict()
|
117 |
|
118 | if error_dict is None:
|
119 | error_dict = value.Dict({'code': num.ToBig(status)})
|
120 |
|
121 | # Always set _error
|
122 | self.mem.SetTryError(error_dict)
|
123 |
|
124 | # TODO: remove _status in favor of _error.code. This is marked in
|
125 | # spec/TODO-deprecate
|
126 | self.mem.SetTryStatus(status)
|
127 | return 0
|
128 |
|
129 |
|
130 | class Failed(vm._Builtin):
|
131 |
|
132 | def __init__(self, mem):
|
133 | # type: (state.Mem) -> None
|
134 | self.mem = mem
|
135 |
|
136 | def Run(self, cmd_val):
|
137 | # type: (cmd_value.Argv) -> int
|
138 | _, arg_r = flag_util.ParseCmdVal('failed', cmd_val)
|
139 |
|
140 | # No args
|
141 | arg_r.Done()
|
142 |
|
143 | # Should we have
|
144 | # failed (_error) ?
|
145 |
|
146 | err = self.mem.TryError()
|
147 | code = err.d.get('code')
|
148 | if code is None:
|
149 | # No error
|
150 | return 1
|
151 |
|
152 | UP_code = code
|
153 | with tagswitch(code) as case:
|
154 | if case(value_e.Int):
|
155 | code = cast(value.Int, UP_code)
|
156 | # return 0 if and only if it failed
|
157 | return 1 if mops.Equal(code.i, mops.ZERO) else 0
|
158 | else:
|
159 | # This should never happen because the interpreter controls the
|
160 | # contents of TryError()
|
161 | raise AssertionError()
|
162 |
|
163 |
|
164 | class Error(vm._Builtin):
|
165 |
|
166 | def __init__(self):
|
167 | # type: () -> None
|
168 | pass
|
169 |
|
170 | def Run(self, cmd_val):
|
171 | # type: (cmd_value.Argv) -> int
|
172 | _, arg_r = flag_util.ParseCmdVal('error',
|
173 | cmd_val,
|
174 | accept_typed_args=True)
|
175 |
|
176 | message = arg_r.Peek()
|
177 | if message is None:
|
178 | raise error.Usage('expected a message to display',
|
179 | cmd_val.arg_locs[0])
|
180 |
|
181 | rd = typed_args.ReaderForProc(cmd_val)
|
182 | # Status 10 is distinct from what the Oils interpreter itself uses. We
|
183 | # use status 3 for expressions and 4 for encode/decode, and 10 "leaves
|
184 | # room" for others.
|
185 | # The user is of course free to choose status 1.
|
186 | status = mops.BigTruncate(rd.NamedInt('code', 10))
|
187 |
|
188 | # attach rest of named args to _error Dict
|
189 | properties = rd.RestNamed()
|
190 | rd.Done()
|
191 |
|
192 | if status == 0:
|
193 | raise error.Usage('status must be a non-zero integer',
|
194 | cmd_val.arg_locs[0])
|
195 |
|
196 | raise error.Structured(status, message, cmd_val.arg_locs[0],
|
197 | properties)
|
198 |
|
199 |
|
200 | class BoolStatus(vm._Builtin):
|
201 |
|
202 | def __init__(self, shell_ex, errfmt):
|
203 | # type: (vm._Executor, ui.ErrorFormatter) -> None
|
204 | self.shell_ex = shell_ex
|
205 | self.errfmt = errfmt
|
206 |
|
207 | def Run(self, cmd_val):
|
208 | # type: (cmd_value.Argv) -> int
|
209 |
|
210 | _, arg_r = flag_util.ParseCmdVal('boolstatus', cmd_val)
|
211 |
|
212 | if arg_r.Peek() is None:
|
213 | e_usage('expected a command to run', loc.Missing)
|
214 |
|
215 | argv, locs = arg_r.Rest2()
|
216 | cmd_val2 = cmd_value.Argv(argv, locs, cmd_val.is_last_cmd,
|
217 | cmd_val.self_obj, cmd_val.proc_args)
|
218 |
|
219 | cmd_st = CommandStatus.CreateNull(alloc_lists=True)
|
220 | run_flags = executor.IS_LAST_CMD if cmd_val.is_last_cmd else 0
|
221 | status = self.shell_ex.RunSimpleCommand(cmd_val2, cmd_st, run_flags)
|
222 |
|
223 | if status not in (0, 1):
|
224 | e_die_status(status,
|
225 | 'boolstatus expected status 0 or 1, got %d' % status,
|
226 | locs[0])
|
227 |
|
228 | return status
|
229 |
|
230 |
|
231 | class Assert(vm._Builtin):
|
232 |
|
233 | def __init__(self, expr_ev, errfmt):
|
234 | # type: (expr_eval.ExprEvaluator, ui.ErrorFormatter) -> None
|
235 | self.expr_ev = expr_ev
|
236 | self.errfmt = errfmt
|
237 | self.f = mylib.Stdout()
|
238 |
|
239 | def _AssertComparison(self, exp, blame_loc):
|
240 | # type: (expr.Compare, loc_t) -> None
|
241 |
|
242 | # We checked exp.ops
|
243 | assert len(exp.comparators) == 1, exp.comparators
|
244 |
|
245 | expected = self.expr_ev.EvalExpr(exp.left, loc.Missing)
|
246 | actual = self.expr_ev.EvalExpr(exp.comparators[0], loc.Missing)
|
247 |
|
248 | if not val_ops.ExactlyEqual(expected, actual, blame_loc):
|
249 | self.f.write('\n')
|
250 | # Long values could also show DIFF, rather than wrapping
|
251 | # We could have assert --diff or something
|
252 | ui.PrettyPrintValue('Expected: ', expected, self.f)
|
253 | ui.PrettyPrintValue('Got: ', actual, self.f)
|
254 |
|
255 | raise error.Expr("Not equal", exp.ops[0])
|
256 |
|
257 | def _AssertExpression(self, val, blame_loc):
|
258 | # type: (value.Expr, loc_t) -> None
|
259 |
|
260 | # Special case for assert [true === f()]
|
261 | exp = val.e
|
262 | UP_exp = exp
|
263 | with tagswitch(exp) as case:
|
264 | if case(expr_e.Compare):
|
265 | exp = cast(expr.Compare, UP_exp)
|
266 |
|
267 | # Only assert [x === y] is treated as special
|
268 | # Not assert [x === y === z]
|
269 | if len(exp.ops) == 1 and exp.ops[0].id == Id.Expr_TEqual:
|
270 | self._AssertComparison(exp, blame_loc)
|
271 | return
|
272 |
|
273 | # Any other expression
|
274 | result = self.expr_ev.EvalExpr(val.e, blame_loc)
|
275 | b = val_ops.ToBool(result)
|
276 | if not b:
|
277 | # Don't print the value for something like assert [x < 4]
|
278 | #self.f.write('\n')
|
279 | #ui.PrettyPrintValue("Expression isn't true: ", result, self.f)
|
280 | raise error.Expr("Expression isn't true", blame_loc)
|
281 |
|
282 | def Run(self, cmd_val):
|
283 | # type: (cmd_value.Argv) -> int
|
284 |
|
285 | _, arg_r = flag_util.ParseCmdVal('assert',
|
286 | cmd_val,
|
287 | accept_typed_args=True)
|
288 |
|
289 | rd = typed_args.ReaderForProc(cmd_val)
|
290 | val = rd.PosValue()
|
291 | rd.Done()
|
292 |
|
293 | UP_val = val
|
294 | with tagswitch(val) as case:
|
295 | if case(value_e.Expr): # Destructured assert [true === f()]
|
296 | val = cast(value.Expr, UP_val)
|
297 | self._AssertExpression(val, rd.LeftParenToken())
|
298 | else:
|
299 | b = val_ops.ToBool(val)
|
300 | if not b:
|
301 | # assert (42 === null) should be written
|
302 | # assert [42 === null] to get a better error message
|
303 | # But show the value anyway
|
304 | self.f.write('\n')
|
305 | ui.PrettyPrintValue("Value isn't true: ", val, self.f)
|
306 | raise error.Expr('assertion', rd.LeftParenToken())
|
307 |
|
308 | return 0
|