1 | from __future__ import print_function
|
2 |
|
3 | from errno import EINTR
|
4 |
|
5 | from _devbuild.gen.syntax_asdl import loc, loc_t, command_t
|
6 | from _devbuild.gen.value_asdl import (value, value_e, value_t, eggex_ops,
|
7 | eggex_ops_t, regex_match, RegexMatch,
|
8 | Obj)
|
9 | from core import error
|
10 | from core.error import e_die
|
11 | from display import ui
|
12 | from mycpp import mops
|
13 | from mycpp import mylib
|
14 | from mycpp.mylib import tagswitch, log
|
15 | from ysh import regex_translate
|
16 |
|
17 | from typing import TYPE_CHECKING, cast, Dict, List, Optional
|
18 |
|
19 | import libc
|
20 | import posix_ as posix
|
21 |
|
22 | _ = log
|
23 |
|
24 | if TYPE_CHECKING:
|
25 | from core import state
|
26 |
|
27 |
|
28 | def ToInt(val, msg, blame_loc):
|
29 | # type: (value_t, str, loc_t) -> int
|
30 | UP_val = val
|
31 | if val.tag() == value_e.Int:
|
32 | val = cast(value.Int, UP_val)
|
33 | return mops.BigTruncate(val.i)
|
34 |
|
35 | raise error.TypeErr(val, msg, blame_loc)
|
36 |
|
37 |
|
38 | def ToFloat(val, msg, blame_loc):
|
39 | # type: (value_t, str, loc_t) -> float
|
40 | UP_val = val
|
41 | if val.tag() == value_e.Float:
|
42 | val = cast(value.Float, UP_val)
|
43 | return val.f
|
44 |
|
45 | raise error.TypeErr(val, msg, blame_loc)
|
46 |
|
47 |
|
48 | def ToStr(val, msg, blame_loc):
|
49 | # type: (value_t, str, loc_t) -> str
|
50 | UP_val = val
|
51 | if val.tag() == value_e.Str:
|
52 | val = cast(value.Str, UP_val)
|
53 | return val.s
|
54 |
|
55 | raise error.TypeErr(val, msg, blame_loc)
|
56 |
|
57 |
|
58 | def ToList(val, msg, blame_loc):
|
59 | # type: (value_t, str, loc_t) -> List[value_t]
|
60 | UP_val = val
|
61 | if val.tag() == value_e.List:
|
62 | val = cast(value.List, UP_val)
|
63 | return val.items
|
64 |
|
65 | raise error.TypeErr(val, msg, blame_loc)
|
66 |
|
67 |
|
68 | def ToDict(val, msg, blame_loc):
|
69 | # type: (value_t, str, loc_t) -> Dict[str, value_t]
|
70 | UP_val = val
|
71 | if val.tag() == value_e.Dict:
|
72 | val = cast(value.Dict, UP_val)
|
73 | return val.d
|
74 |
|
75 | raise error.TypeErr(val, msg, blame_loc)
|
76 |
|
77 |
|
78 | def ToCommandFrag(val, msg, blame_loc):
|
79 | # type: (value_t, str, loc_t) -> command_t
|
80 | UP_val = val
|
81 | if val.tag() == value_e.CommandFrag:
|
82 | val = cast(value.CommandFrag, UP_val)
|
83 | return val.c
|
84 |
|
85 | raise error.TypeErr(val, msg, blame_loc)
|
86 |
|
87 |
|
88 | def Stringify(val, blame_loc, op_desc):
|
89 | # type: (value_t, loc_t, str) -> str
|
90 | """
|
91 | Args:
|
92 | op_desc: could be empty string ''
|
93 | or 'Expr Sub ' or 'Expr Splice ', with trailing space
|
94 |
|
95 | Used by:
|
96 |
|
97 | $[x] Expr Sub - stringify operator
|
98 | @[x] Expr splice - each element is stringified
|
99 | @x Splice value
|
100 |
|
101 | str() Builtin function
|
102 | join() Each element is stringified, e.g. join([1,2])
|
103 | Not sure I like join([null, true]), but it's consistent
|
104 | Str.replace() ^"x = $x" after eggex conversion function
|
105 | """
|
106 | if blame_loc is None:
|
107 | blame_loc = loc.Missing
|
108 |
|
109 | UP_val = val
|
110 | with tagswitch(val) as case:
|
111 | if case(value_e.Str): # trivial case
|
112 | val = cast(value.Str, UP_val)
|
113 | return val.s
|
114 |
|
115 | elif case(value_e.Null):
|
116 | s = 'null' # JSON spelling
|
117 |
|
118 | elif case(value_e.Bool):
|
119 | val = cast(value.Bool, UP_val)
|
120 | s = 'true' if val.b else 'false' # JSON spelling
|
121 |
|
122 | elif case(value_e.Int):
|
123 | val = cast(value.Int, UP_val)
|
124 | # e.g. decimal '42', the only sensible representation
|
125 | s = mops.ToStr(val.i)
|
126 |
|
127 | elif case(value_e.Float):
|
128 | val = cast(value.Float, UP_val)
|
129 | s = str(val.f)
|
130 |
|
131 | elif case(value_e.Eggex):
|
132 | val = cast(value.Eggex, UP_val)
|
133 | s = regex_translate.AsPosixEre(val) # lazily converts to ERE
|
134 |
|
135 | else:
|
136 | pass # mycpp workaround
|
137 |
|
138 | if val.tag() == value_e.List:
|
139 | # Special error message for using the wrong sigil, or maybe join
|
140 | raise error.TypeErrVerbose(
|
141 | "%sgot a List, which can't be stringified (OILS-ERR-203)" %
|
142 | op_desc, blame_loc)
|
143 |
|
144 | raise error.TypeErr(
|
145 | val,
|
146 | "%sexpected one of (Null Bool Int Float Str Eggex)" % op_desc,
|
147 | blame_loc)
|
148 |
|
149 | return s
|
150 |
|
151 |
|
152 | def ToShellArray(val, blame_loc, prefix=''):
|
153 | # type: (value_t, loc_t, str) -> List[str]
|
154 | """
|
155 | Used by
|
156 |
|
157 | @[x] expression splice
|
158 | @x splice value
|
159 |
|
160 | Dicts do NOT get spliced, but they iterate over their keys
|
161 | So this function NOT use Iterator.
|
162 | """
|
163 | UP_val = val
|
164 | with tagswitch(val) as case2:
|
165 | if case2(value_e.List):
|
166 | val = cast(value.List, UP_val)
|
167 | strs = [] # type: List[str]
|
168 | # Note: it would be nice to add the index to the error message
|
169 | # prefix, WITHOUT allocating a string for every item
|
170 | for item in val.items:
|
171 | strs.append(Stringify(item, blame_loc, prefix))
|
172 |
|
173 | # I thought about getting rid of this to keep OSH and YSH separate,
|
174 | # but:
|
175 | # - readarray/mapfile returns bash array (ysh-user-feedback depends on it)
|
176 | # - ysh-options tests parse_at too
|
177 | elif case2(value_e.BashArray):
|
178 | val = cast(value.BashArray, UP_val)
|
179 | strs = val.strs
|
180 |
|
181 | else:
|
182 | raise error.TypeErr(val, "%sexpected List" % prefix, blame_loc)
|
183 |
|
184 | return strs
|
185 |
|
186 |
|
187 | class Iterator(object):
|
188 | """Interface for various types of for loop."""
|
189 |
|
190 | def __init__(self):
|
191 | # type: () -> None
|
192 | self.i = 0
|
193 |
|
194 | def Index(self):
|
195 | # type: () -> int
|
196 | return self.i
|
197 |
|
198 | def Next(self):
|
199 | # type: () -> None
|
200 | self.i += 1
|
201 |
|
202 | def FirstValue(self):
|
203 | # type: () -> Optional[value_t]
|
204 | """Return a value, or None if done
|
205 |
|
206 | e.g. return Dict key or List value
|
207 | """
|
208 | raise NotImplementedError()
|
209 |
|
210 | def SecondValue(self):
|
211 | # type: () -> value_t
|
212 | """Return Dict value or FAIL"""
|
213 | raise AssertionError("Shouldn't have called this")
|
214 |
|
215 |
|
216 | class StdinIterator(Iterator):
|
217 | """ for x in <> { """
|
218 |
|
219 | def __init__(self, blame_loc):
|
220 | # type: (loc_t) -> None
|
221 | Iterator.__init__(self)
|
222 | self.blame_loc = blame_loc
|
223 | self.f = mylib.Stdin()
|
224 |
|
225 | def FirstValue(self):
|
226 | # type: () -> Optional[value_t]
|
227 |
|
228 | # line, eof = read_osh.ReadLineSlowly(None, with_eol=False)
|
229 | try:
|
230 | line = self.f.readline()
|
231 | except (IOError, OSError) as e: # signals
|
232 | if e.errno == EINTR:
|
233 | # Caller will can run traps with cmd_ev, like ReadLineSlowly
|
234 | return value.Interrupted
|
235 | else:
|
236 | # For possible errors from f.readline(), see
|
237 | # man read
|
238 | # man getline
|
239 | # e.g.
|
240 | # - ENOMEM getline() allocation failure
|
241 | # - EISDIR getline() read from directory descriptor!
|
242 | #
|
243 | # Note: the read builtin returns status 1 for EISDIR.
|
244 | #
|
245 | # We'll raise a top-level error like Python. (Awk prints a
|
246 | # warning message)
|
247 | e_die("I/O error in for <> loop: %s" % posix.strerror(e.errno),
|
248 | self.blame_loc)
|
249 |
|
250 | #log('L %r', line)
|
251 | if len(line) == 0:
|
252 | return None # Done
|
253 | elif line.endswith('\n'):
|
254 | # TODO: optimize this to prevent extra garbage
|
255 | line = line[:-1]
|
256 |
|
257 | return value.Str(line)
|
258 |
|
259 |
|
260 | class ArrayIter(Iterator):
|
261 | """ for x in 1 2 3 { """
|
262 |
|
263 | def __init__(self, strs):
|
264 | # type: (List[str]) -> None
|
265 | Iterator.__init__(self)
|
266 | self.strs = strs
|
267 | self.n = len(strs)
|
268 |
|
269 | def FirstValue(self):
|
270 | # type: () -> Optional[value_t]
|
271 | if self.i == self.n:
|
272 | return None
|
273 | return value.Str(self.strs[self.i])
|
274 |
|
275 |
|
276 | class RangeIterator(Iterator):
|
277 | """ for x in (m:n) { """
|
278 |
|
279 | def __init__(self, val):
|
280 | # type: (value.Range) -> None
|
281 | Iterator.__init__(self)
|
282 | self.val = val
|
283 |
|
284 | def FirstValue(self):
|
285 | # type: () -> Optional[value_t]
|
286 | if self.val.lower + self.i >= self.val.upper:
|
287 | return None
|
288 |
|
289 | # TODO: range should be BigInt too
|
290 | return value.Int(mops.IntWiden(self.val.lower + self.i))
|
291 |
|
292 |
|
293 | class ListIterator(Iterator):
|
294 | """ for x in (mylist) { """
|
295 |
|
296 | def __init__(self, val):
|
297 | # type: (value.List) -> None
|
298 | Iterator.__init__(self)
|
299 | self.val = val
|
300 | self.n = len(val.items)
|
301 |
|
302 | def FirstValue(self):
|
303 | # type: () -> Optional[value_t]
|
304 | if self.i == self.n:
|
305 | return None
|
306 | return self.val.items[self.i]
|
307 |
|
308 |
|
309 | class DictIterator(Iterator):
|
310 | """ for x in (mydict) { """
|
311 |
|
312 | def __init__(self, val):
|
313 | # type: (value.Dict) -> None
|
314 | Iterator.__init__(self)
|
315 |
|
316 | # TODO: Don't materialize these Lists
|
317 | self.keys = val.d.keys() # type: List[str]
|
318 | self.values = val.d.values() # type: List[value_t]
|
319 |
|
320 | self.n = len(val.d)
|
321 | assert self.n == len(self.keys)
|
322 |
|
323 | def FirstValue(self):
|
324 | # type: () -> value_t
|
325 | if self.i == self.n:
|
326 | return None
|
327 | return value.Str(self.keys[self.i])
|
328 |
|
329 | def SecondValue(self):
|
330 | # type: () -> value_t
|
331 | return self.values[self.i]
|
332 |
|
333 |
|
334 | def ToBool(val):
|
335 | # type: (value_t) -> bool
|
336 | """Convert any value to a boolean.
|
337 |
|
338 | TODO: expose this as Bool(x), like Python's bool(x).
|
339 | """
|
340 | UP_val = val
|
341 | with tagswitch(val) as case:
|
342 | if case(value_e.Undef):
|
343 | return False
|
344 |
|
345 | elif case(value_e.Null):
|
346 | return False
|
347 |
|
348 | elif case(value_e.Str):
|
349 | val = cast(value.Str, UP_val)
|
350 | return len(val.s) != 0
|
351 |
|
352 | # OLD TYPES
|
353 | elif case(value_e.BashArray):
|
354 | val = cast(value.BashArray, UP_val)
|
355 | return len(val.strs) != 0
|
356 |
|
357 | elif case(value_e.BashAssoc):
|
358 | val = cast(value.BashAssoc, UP_val)
|
359 | return len(val.d) != 0
|
360 |
|
361 | elif case(value_e.Bool):
|
362 | val = cast(value.Bool, UP_val)
|
363 | return val.b
|
364 |
|
365 | elif case(value_e.Int):
|
366 | val = cast(value.Int, UP_val)
|
367 | return not mops.Equal(val.i, mops.BigInt(0))
|
368 |
|
369 | elif case(value_e.Float):
|
370 | val = cast(value.Float, UP_val)
|
371 | return val.f != 0.0
|
372 |
|
373 | elif case(value_e.List):
|
374 | val = cast(value.List, UP_val)
|
375 | return len(val.items) > 0
|
376 |
|
377 | elif case(value_e.Dict):
|
378 | val = cast(value.Dict, UP_val)
|
379 | return len(val.d) > 0
|
380 |
|
381 | else:
|
382 | return True # all other types are Truthy
|
383 |
|
384 |
|
385 | def ExactlyEqual(left, right, blame_loc):
|
386 | # type: (value_t, value_t, loc_t) -> bool
|
387 |
|
388 | if left.tag() == value_e.Float or right.tag() == value_e.Float:
|
389 | raise error.TypeErrVerbose(
|
390 | "Equality isn't defined on Float values (OILS-ERR-202)", blame_loc)
|
391 |
|
392 | if left.tag() != right.tag():
|
393 | return False
|
394 |
|
395 | UP_left = left
|
396 | UP_right = right
|
397 | with tagswitch(left) as case:
|
398 | if case(value_e.Undef):
|
399 | return True # there's only one Undef
|
400 |
|
401 | elif case(value_e.Null):
|
402 | return True # there's only one Null
|
403 |
|
404 | elif case(value_e.Bool):
|
405 | left = cast(value.Bool, UP_left)
|
406 | right = cast(value.Bool, UP_right)
|
407 | return left.b == right.b
|
408 |
|
409 | elif case(value_e.Int):
|
410 | left = cast(value.Int, UP_left)
|
411 | right = cast(value.Int, UP_right)
|
412 | return mops.Equal(left.i, right.i)
|
413 |
|
414 | elif case(value_e.Float):
|
415 | raise AssertionError()
|
416 |
|
417 | elif case(value_e.Str):
|
418 | left = cast(value.Str, UP_left)
|
419 | right = cast(value.Str, UP_right)
|
420 | return left.s == right.s
|
421 |
|
422 | elif case(value_e.BashArray):
|
423 | left = cast(value.BashArray, UP_left)
|
424 | right = cast(value.BashArray, UP_right)
|
425 | if len(left.strs) != len(right.strs):
|
426 | return False
|
427 |
|
428 | for i in xrange(0, len(left.strs)):
|
429 | if left.strs[i] != right.strs[i]:
|
430 | return False
|
431 |
|
432 | return True
|
433 |
|
434 | elif case(value_e.List):
|
435 | left = cast(value.List, UP_left)
|
436 | right = cast(value.List, UP_right)
|
437 | if len(left.items) != len(right.items):
|
438 | return False
|
439 |
|
440 | for i in xrange(0, len(left.items)):
|
441 | if not ExactlyEqual(left.items[i], right.items[i], blame_loc):
|
442 | return False
|
443 |
|
444 | return True
|
445 |
|
446 | elif case(value_e.BashAssoc):
|
447 | left = cast(value.Dict, UP_left)
|
448 | right = cast(value.Dict, UP_right)
|
449 | if len(left.d) != len(right.d):
|
450 | return False
|
451 |
|
452 | for k in left.d.keys():
|
453 | if k not in right.d or right.d[k] != left.d[k]:
|
454 | return False
|
455 |
|
456 | return True
|
457 |
|
458 | elif case(value_e.Dict):
|
459 | left = cast(value.Dict, UP_left)
|
460 | right = cast(value.Dict, UP_right)
|
461 | if len(left.d) != len(right.d):
|
462 | return False
|
463 |
|
464 | for k in left.d.keys():
|
465 | if (k not in right.d or
|
466 | not ExactlyEqual(right.d[k], left.d[k], blame_loc)):
|
467 | return False
|
468 |
|
469 | return True
|
470 |
|
471 | raise error.TypeErrVerbose(
|
472 | "Can't compare two values of type %s" % ui.ValType(left), blame_loc)
|
473 |
|
474 |
|
475 | def Contains(needle, haystack):
|
476 | # type: (value_t, value_t) -> bool
|
477 | """Haystack must be a Dict.
|
478 |
|
479 | We should have mylist->find(x) !== -1 for searching through a List.
|
480 | Things with different perf characteristics should look different.
|
481 | """
|
482 | UP_haystack = haystack
|
483 | with tagswitch(haystack) as case:
|
484 | if case(value_e.Dict):
|
485 | haystack = cast(value.Dict, UP_haystack)
|
486 | s = ToStr(needle, "LHS of 'in' should be Str", loc.Missing)
|
487 | return s in haystack.d
|
488 |
|
489 | else:
|
490 | raise error.TypeErr(haystack, "RHS of 'in' should be Dict",
|
491 | loc.Missing)
|
492 |
|
493 | return False
|
494 |
|
495 |
|
496 | def MatchRegex(left, right, mem):
|
497 | # type: (value_t, value_t, Optional[state.Mem]) -> bool
|
498 | """
|
499 | Args:
|
500 | mem: Whether to set or clear matches
|
501 | """
|
502 | UP_right = right
|
503 |
|
504 | with tagswitch(right) as case:
|
505 | if case(value_e.Str): # plain ERE
|
506 | right = cast(value.Str, UP_right)
|
507 |
|
508 | right_s = right.s
|
509 | regex_flags = 0
|
510 | capture = eggex_ops.No # type: eggex_ops_t
|
511 |
|
512 | elif case(value_e.Eggex):
|
513 | right = cast(value.Eggex, UP_right)
|
514 |
|
515 | right_s = regex_translate.AsPosixEre(right)
|
516 | regex_flags = regex_translate.LibcFlags(right.canonical_flags)
|
517 | capture = eggex_ops.Yes(right.convert_funcs, right.convert_toks,
|
518 | right.capture_names)
|
519 |
|
520 | else:
|
521 | raise error.TypeErr(right, 'Expected Str or Regex for RHS of ~',
|
522 | loc.Missing)
|
523 |
|
524 | UP_left = left
|
525 | left_s = None # type: str
|
526 | with tagswitch(left) as case:
|
527 | if case(value_e.Str):
|
528 | left = cast(value.Str, UP_left)
|
529 | left_s = left.s
|
530 | else:
|
531 | raise error.TypeErrVerbose('LHS must be a string', loc.Missing)
|
532 |
|
533 | indices = libc.regex_search(right_s, regex_flags, left_s, 0)
|
534 | if indices is not None:
|
535 | if mem:
|
536 | mem.SetRegexMatch(RegexMatch(left_s, indices, capture))
|
537 | return True
|
538 | else:
|
539 | if mem:
|
540 | mem.SetRegexMatch(regex_match.No)
|
541 | return False
|
542 |
|
543 |
|
544 | def IndexMetaMethod(obj):
|
545 | # type: (Obj) -> Optional[value_t]
|
546 | """
|
547 | Returns value.{BuiltinFunc,Func} -- but not callable Obj?
|
548 | """
|
549 | if not obj.prototype:
|
550 | return None
|
551 | index_val = obj.prototype.d.get('__index__')
|
552 | if not index_val:
|
553 | return None
|
554 |
|
555 | if index_val.tag() not in (value_e.BuiltinFunc, value_e.Func):
|
556 | return None
|
557 |
|
558 | return index_val
|
559 |
|
560 |
|
561 | # vim: sw=4
|