OILS / frontend / id_kind_def.py View on Github | oils.pub

816 lines, 553 significant
1#!/usr/bin/env python2
2# Copyright 2016 Andy Chu. All rights reserved.
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8"""
9id_kind_def.py - Id and Kind definitions, stored in Token
10
11NOTE: If this file changes, rebuild it with build/py.sh all
12"""
13from __future__ import print_function
14
15from _devbuild.gen.types_asdl import (bool_arg_type_e, bool_arg_type_t)
16#from mycpp.mylib import log
17
18from typing import List, Tuple, Dict, Optional, TYPE_CHECKING
19if TYPE_CHECKING: # avoid circular build deps
20 from _devbuild.gen.id_kind_asdl import Id_t, Kind_t
21
22
23class IdSpec(object):
24 """Identifiers that form the "spine" of the shell program
25 representation."""
26
27 def __init__(self, kind_lookup, bool_ops):
28 # type: (Dict[int, int], Dict[int, bool_arg_type_t]) -> None
29 self.id_str2int = {} # type: Dict[str, int]
30 self.kind_str2int = {} # type: Dict[str, int]
31
32 self.kind_lookup = kind_lookup # Id int -> Kind int
33 self.kind_name_list = [] # type: List[str]
34 self.kind_sizes = [] # type: List[int] # optional stats
35
36 self.lexer_pairs = {} # type: Dict[int, List[Tuple[bool, str, int]]]
37 self.bool_ops = bool_ops # type: Dict[int, bool_arg_type_t]
38
39 # Incremented on each method call
40 # IMPORTANT: 1-based indices match what asdl/gen_python.py does!!!
41 self.id_index = 1
42 self.kind_index = 1
43
44 def LexerPairs(self, kind):
45 # type: (Kind_t) -> List[Tuple[bool, str, Id_t]]
46 result = []
47 for is_regex, pat, id_ in self.lexer_pairs[kind]:
48 result.append((is_regex, pat, id_))
49 return result
50
51 def _AddId(self, id_name, kind=None):
52 # type: (str, Optional[int]) -> int
53 """
54 Args:
55 id_name: e.g. BoolBinary_Equal
56 kind: override autoassignment. For AddBoolBinaryForBuiltin
57 """
58 t = self.id_index
59
60 self.id_str2int[id_name] = t
61
62 if kind is None:
63 kind = self.kind_index
64 self.kind_lookup[t] = kind
65
66 self.id_index += 1 # mutate last
67 return t # the index we used
68
69 def _AddKind(self, kind_name):
70 # type: (str) -> None
71 self.kind_str2int[kind_name] = self.kind_index
72 #log('%s = %d', kind_name, self.kind_index)
73 self.kind_index += 1
74 self.kind_name_list.append(kind_name)
75
76 def AddKind(self, kind_name, tokens):
77 # type: (str, List[str]) -> None
78 assert isinstance(tokens, list), tokens
79
80 for name in tokens:
81 id_name = '%s_%s' % (kind_name, name)
82 self._AddId(id_name)
83
84 # Must be after adding Id
85 self._AddKind(kind_name)
86 self.kind_sizes.append(len(tokens)) # debug info
87
88 def AddKindPairs(self, kind_name, pairs):
89 # type: (str, List[Tuple[str, str]]) -> None
90 assert isinstance(pairs, list), pairs
91
92 lexer_pairs = []
93 for name, char_pat in pairs:
94 id_name = '%s_%s' % (kind_name, name)
95 id_int = self._AddId(id_name)
96 # After _AddId
97 lexer_pairs.append((False, char_pat, id_int)) # Constant
98
99 self.lexer_pairs[self.kind_index] = lexer_pairs
100
101 # Must be after adding Id
102 self._AddKind(kind_name)
103 self.kind_sizes.append(len(pairs)) # debug info
104
105 def AddBoolKind(
106 self,
107 kind_name, # type: str
108 arg_type_pairs, # type: List[Tuple[bool_arg_type_t, List[Tuple[str, str]]]]
109 ):
110 # type: (...) -> None
111 """
112 Args:
113 kind_name: string
114 arg_type_pairs: dictionary of bool_arg_type_e -> []
115 """
116 lexer_pairs = []
117 num_tokens = 0
118 for arg_type, pairs in arg_type_pairs:
119 #print(arg_type, pairs)
120
121 for name, char_pat in pairs:
122 # BoolUnary_f, BoolBinary_eq, BoolBinary_NEqual
123 id_name = '%s_%s' % (kind_name, name)
124 id_int = self._AddId(id_name)
125 self.AddBoolOp(id_int, arg_type) # register type
126 lexer_pairs.append((False, char_pat, id_int)) # constant
127
128 num_tokens += len(pairs)
129
130 self.lexer_pairs[self.kind_index] = lexer_pairs
131
132 # Must do this after _AddId()
133 self._AddKind(kind_name)
134 self.kind_sizes.append(num_tokens) # debug info
135
136 def AddBoolBinaryForBuiltin(self, id_name, kind):
137 # type: (str, int) -> int
138 """For [ = ] [ == ] and [ != ].
139
140 These operators are NOT added to the lexer. The are "lexed" as
141 word.String.
142 """
143 id_name = 'BoolBinary_%s' % id_name
144 id_int = self._AddId(id_name, kind=kind)
145 self.AddBoolOp(id_int, bool_arg_type_e.Str)
146 return id_int
147
148 def AddBoolOp(self, id_int, arg_type):
149 # type: (int, bool_arg_type_t) -> None
150 """Associate an ID integer with an bool_arg_type_e."""
151 self.bool_ops[id_int] = arg_type
152
153
154def AddKinds(spec):
155 # type: (IdSpec) -> None
156
157 # A compound word, in arith context, boolean context, or command context.
158 # A['foo'] A["foo"] A[$foo] A["$foo"] A[${foo}] A["${foo}"]
159 spec.AddKind('Word', ['Compound'])
160
161 # Token IDs in Kind.Arith are first to make the TDOP precedence table
162 # small.
163 #
164 # NOTE: Could share Op_Pipe, Op_Amp, Op_DAmp, Op_Semi, Op_LParen, etc.
165 # Actually all of Arith could be folded into Op, because we are using
166 # WordParser._ReadArithWord vs. WordParser._ReadWord.
167 spec.AddKindPairs(
168 'Arith',
169 [
170 ('Semi', ';'), # ternary for loop only
171 ('Comma', ','), # function call and C comma operator
172 ('Plus', '+'),
173 ('Minus', '-'),
174 ('Star', '*'),
175 ('Slash', '/'),
176 ('Percent', '%'),
177 ('DPlus', '++'),
178 ('DMinus', '--'),
179 ('DStar', '**'),
180 ('LParen', '('),
181 ('RParen', ')'), # grouping and function call extension
182 ('LBracket', '['),
183 ('RBracket', ']'), # array and assoc array subscript
184 ('RBrace', '}'), # for end of var sub
185
186 # Logical Ops
187 ('QMark', '?'),
188 ('Colon', ':'), # Ternary Op: a < b ? 0 : 1
189 ('LessEqual', '<='),
190 ('Less', '<'),
191 ('GreatEqual', '>='),
192 ('Great', '>'),
193 ('DEqual', '=='),
194 ('NEqual', '!='),
195 # note: these 3 are not in YSH Expr. (Could be used in find dialect.)
196 ('DAmp', '&&'),
197 ('DPipe', '||'),
198 ('Bang', '!'),
199
200 # Bitwise ops
201 ('DGreat', '>>'),
202 ('DLess', '<<'),
203 # YSH: ^ is exponent
204 ('Amp', '&'),
205 ('Pipe', '|'),
206 ('Caret', '^'),
207 ('Tilde', '~'),
208 ('Equal', '='),
209
210 # Augmented Assignment for $(( ))
211 # Must match the list in osh/arith_parse.py
212 # YSH has **= //= like Python
213 ('PlusEqual', '+='),
214 ('MinusEqual', '-='),
215 ('StarEqual', '*='),
216 ('SlashEqual', '/='),
217 ('PercentEqual', '%='),
218 ('DGreatEqual', '>>='),
219 ('DLessEqual', '<<='),
220 ('AmpEqual', '&='),
221 ('CaretEqual', '^='),
222 ('PipeEqual', '|='),
223 ])
224
225 spec.AddKind('Eof', ['Real', 'RParen', 'Backtick'])
226
227 spec.AddKind('Undefined', ['Tok']) # for initial state
228
229 # The Unknown kind is used when we lex something, but it's invalid.
230 # Examples:
231 # ${^}
232 # $'\z' Such bad codes are accepted in OSH, when no_parse_backslash is
233 # off, so we have to lex them.
234 # (x == y) should used === or ~==
235 spec.AddKind('Unknown',
236 ['Tok', 'Backslash', 'DEqual', 'DAmp', 'DPipe', 'DDot'])
237
238 spec.AddKind('Eol', ['Tok']) # no more tokens on line (\0)
239
240 # Ignored_Newline is for J8 lexing to count lines
241 spec.AddKind('Ignored', ['LineCont', 'Space', 'Comment', 'Newline'])
242
243 # Id.WS_Space is for lex_mode_e.ShCommand; Id.Ignored_Space is for
244 # lex_mode_e.Arith
245 spec.AddKind('WS', ['Space'])
246
247 spec.AddKind(
248 'Lit',
249 [
250 'Chars',
251 'CharsWithoutPrefix', # for stripping leading whitespace
252 'VarLike',
253 'ArrayLhsOpen',
254 'ArrayLhsClose',
255 'Splice', # @func(a, b)
256 'AtLBracket', # @[split(x)]
257 'AtLBraceDot', # @{.myproc arg1} should be builtin_sub
258 'Other',
259 'EscapedChar', # \* is escaped
260 'LBracket',
261 'RBracket', # for assoc array literals, static globs
262 'Star',
263 'QMark',
264 # Either brace expansion or keyword for { and }
265 'LBrace',
266 'RBrace',
267 'Comma',
268 'Equals', # For = f()
269 'Dollar', # detecting 'echo $'
270 'DRightBracket', # the ]] that matches [[, NOT a keyword
271 'Tilde', # tilde expansion
272 'Pound', # for comment or VarOp state
273 'TPound', # for doc comments like ###
274 'TDot', # for multiline commands ...
275 'Slash',
276 'Percent', # / # % for patsub, NOT unary op
277 'Colon', # x=foo:~:~root needs tilde expansion
278 'Digits', # for lex_mode_e.Arith
279 'At', # for ${a[@]} in lex_mode_e.Arith, and detecting @[]
280 'ArithVarLike', # for $((var+1)). Distinct from Lit_VarLike 'var='
281 'BadBackslash', # for "\z", not Id.Unknown_Backslash because it's a
282 # syntax error in YSH, but NOT OSH
283 'CompDummy', # A fake Lit_* token to get partial words during
284 # completion
285 'Number',
286 'RedirVarName' # "{myvar}", as in {myvar}>out.txt (and on its own)
287 ])
288
289 # For recognizing \` and \" and \\ within backticks. There's an extra layer
290 # of backslash quoting.
291 spec.AddKind('Backtick', ['Right', 'Quoted', 'DoubleQuote', 'Other'])
292
293 spec.AddKind('History', ['Op', 'Num', 'Search', 'Other'])
294
295 spec.AddKind(
296 'Op',
297 [
298 'Newline', # mostly equivalent to SEMI
299 'Amp', # &
300 'Pipe', # |
301 'PipeAmp', # |& -- bash extension for stderr
302 'DAmp', # &&
303 'DPipe', # ||
304 'Semi', # ;
305 'DSemi', # ;; for case
306 'SemiAmp', # ;& for case
307 'DSemiAmp', # ;;& for case
308 'LParen', # For subshell. Not Kind.Left because it's NOT a WordPart.
309 'RParen', # Default, will be translated to Id.Right_*
310 'DLeftParen',
311 'DRightParen',
312
313 # for [[ ]] language
314 'Less', # <
315 'Great', # >
316 'Bang', # !
317
318 # YSH [] {}
319 'LBracket',
320 'RBracket',
321 'LBrace',
322 'RBrace',
323 ])
324
325 # YSH expressions use Kind.Expr and Kind.Arith (further below)
326 spec.AddKind(
327 'Expr',
328 [
329 'Reserved', # <- means nothing but it's reserved now
330 'Symbol', # %foo
331 'Name',
332 'DecInt',
333 'BinInt',
334 'OctInt',
335 'HexInt',
336 'Float',
337 'Bang', # eggex !digit, ![a-z]
338 'Dot',
339 'DDotLessThan',
340 'DDotEqual',
341 'Colon', # mylist:pop()
342 'RArrow',
343 'RDArrow',
344 'DSlash', # integer division
345 'TEqual',
346 'NotDEqual',
347 'TildeDEqual', # === !== ~==
348 'At',
349 'DoubleAt', # splice operators
350 'Ellipsis', # for varargs
351 'Dollar', # legacy regex
352 'NotTilde', # !~
353 'DTilde',
354 'NotDTilde', # ~~ !~~
355 'DStarEqual', # **=, which bash doesn't have
356 'DSlashEqual', # //=, which bash doesn't have
357 'CastedDummy', # Used for @() $() (words in lex_mode_e.ShCommand)
358 # and ${} '' "" (and all other strings)
359
360 # Constants
361 'Null',
362 'True',
363 'False',
364
365 # Keywords are resolved after lexing, but otherwise behave like tokens.
366 'And',
367 'Or',
368 'Not',
369
370 # List comprehensions
371 'For',
372 'Is',
373 'In',
374 'If',
375 'Else',
376 'Capture',
377 'As',
378
379 # Unused
380 'Func',
381 'Proc',
382 ])
383
384 # For C-escaped strings.
385 spec.AddKind(
386 'Char',
387 [
388 'OneChar',
389 'Stop',
390 'Hex', # \xff
391 'YHex', # \yff for J8 notation
392
393 # Two variants of Octal: \377, and \0377.
394 'Octal3',
395 'Octal4',
396 'Unicode4',
397 'SurrogatePair', # JSON
398 'Unicode8', # bash
399 'UBraced',
400 'Pound', # YSH
401 'AsciiControl', # \x01-\x1f, what's disallowed in JSON
402 ])
403
404 # For lex_mode_e.BashRegex
405 # Bash treats ( | ) as special, and space is allowed within ()
406 # Note Id.Op_RParen -> Id.Right_BashRegex with lexer hint
407 spec.AddKind('BashRegex', ['LParen', 'AllowedInParens'])
408
409 spec.AddKind(
410 'Eggex',
411 [
412 'Start', # ^ or %start
413 'End', # $ or %end
414 'Dot', # . or dot
415 # Future: %boundary generates \b in Python/Perl, etc.
416 ])
417
418 spec.AddKind(
419 'Redir',
420 [
421 'Less', # < stdin
422 'Great', # > stdout
423 'DLess', # << here doc redirect
424 'TLess', # <<< bash only here string
425 'DGreat', # >> append stdout
426 'GreatAnd', # >& descriptor redirect
427 'LessAnd', # <& descriptor redirect
428 'DLessDash', # <<- here doc redirect for tabs?
429 'LessGreat', # <>
430 'Clobber', # >| POSIX?
431 'AndGreat', # bash &> stdout/stderr to file
432 'AndDGreat', # bash &>> stdout/stderr append to file
433
434 #'GreatPlus', # >+ is append in YSH
435 #'DGreatPlus', # >>+ is append to string in YSH
436 ])
437
438 # NOTE: This is for left/right WORDS only. (( is not a word so it doesn't
439 # get that.
440 spec.AddKind(
441 'Left',
442 [
443 'DoubleQuote',
444 'JDoubleQuote', # j" for J8 notation
445 'SingleQuote', # ''
446 'DollarSingleQuote', # $'' for \n escapes
447 'RSingleQuote', # r''
448 'USingleQuote', # u''
449 'BSingleQuote', # b''
450
451 # Multiline versions
452 'TDoubleQuote', # """ """
453 'DollarTDoubleQuote', # $""" """
454 'TSingleQuote', # ''' '''
455 'RTSingleQuote', # r''' '''
456 'UTSingleQuote', # u''' '''
457 'BTSingleQuote', # b''' '''
458 'Backtick', # `
459 'DollarParen', # $(
460 'DollarBrace', # ${
461 'DollarBraceZsh', # ${(foo)
462 'DollarDParen', # $((
463 'DollarBracket', # $[ - synonym for $(( in bash and zsh
464 'AtBracket', # @[expr] array splice in expression mode
465 'DollarDoubleQuote', # $" for bash localized strings
466 'ProcSubIn', # <( )
467 'ProcSubOut', # >( )
468 'AtParen', # @( for split command sub
469 'CaretParen', # ^( for Block literal in expression mode
470 'CaretBracket', # ^[ for Expr literal
471 'CaretBrace', # ^{ for Arglist
472 'CaretDoubleQuote', # ^" for Template
473 'ColonPipe', # :| for word arrays
474 'PercentParen', # legacy %( for word arrays
475 ])
476
477 spec.AddKind(
478 'Right',
479 [
480 'DoubleQuote',
481 'SingleQuote',
482 'Backtick', # `
483 'DollarBrace', # }
484 'DollarDParen', # )) -- really the second one is a PushHint()
485 # ArithSub2 is just Id.Arith_RBracket
486 'DollarDoubleQuote', # "
487 'DollarSingleQuote', # '
488
489 # Disambiguated right parens
490 'Subshell', # )
491 'ShFunction', # )
492 'CasePat', # )
493 'Initializer', # )
494 'ExtGlob', # )
495 'BashRegexGroup', # )
496 'BlockLiteral', # } that matches &{ echo hi }
497 ])
498
499 spec.AddKind('ExtGlob', ['Comma', 'At', 'Star', 'Plus', 'QMark', 'Bang'])
500
501 # First position of var sub ${
502 # Id.VOp2_Pound -- however you can't tell the difference at first! It could
503 # be an op or a name. So it makes sense to base i on the state.
504 # Id.VOp2_At
505 # But then you have AS_STAR, or Id.Arith_Star maybe
506
507 spec.AddKind(
508 'VSub',
509 [
510 'DollarName', # $foo
511 'Name', # 'foo' in ${foo}
512 'Number', # $0 .. $9
513 'Bang', # $!
514 'At', # $@ or [@] for array subscripting
515 'Pound', # $# or ${#var} for length
516 'Dollar', # $$
517 'Star', # $*
518 'Hyphen', # $-
519 'QMark', # $?
520 'Dot', # ${.myproc builtin sub}
521 ])
522
523 spec.AddKindPairs('VTest', [
524 ('ColonHyphen', ':-'),
525 ('Hyphen', '-'),
526 ('ColonEquals', ':='),
527 ('Equals', '='),
528 ('ColonQMark', ':?'),
529 ('QMark', '?'),
530 ('ColonPlus', ':+'),
531 ('Plus', '+'),
532 ])
533
534 # Statically parse @P, so @x etc. is an error.
535 spec.AddKindPairs(
536 'VOp0',
537 [
538 ('Q', '@Q'), # ${x@Q} for quoting
539 ('E', '@E'),
540 ('P', '@P'), # ${PS1@P} for prompt eval
541 ('A', '@A'),
542 ('a', '@a'),
543 ])
544
545 # String removal ops
546 spec.AddKindPairs(
547 'VOp1',
548 [
549 ('Percent', '%'),
550 ('DPercent', '%%'),
551 ('Pound', '#'),
552 ('DPound', '##'),
553 # Case ops, in bash. At least parse them. Execution might require
554 # unicode stuff.
555 ('Caret', '^'),
556 ('DCaret', '^^'),
557 ('Comma', ','),
558 ('DComma', ',,'),
559 ])
560
561 spec.AddKindPairs(
562 'VOpYsh',
563 [
564 ('Pipe', '|'), # ${x|html}
565 ('Space', ' '), # ${x %.3f}
566 ])
567
568 # Not in POSIX, but in Bash
569 spec.AddKindPairs(
570 'VOp2',
571 [
572 ('Slash', '/'), # / for replacement
573 ('Colon', ':'), # : for slicing
574 ('LBracket', '['), # [ for indexing
575 ('RBracket', ']'), # ] for indexing
576 ])
577
578 # Can only occur after ${!prefix@}
579 spec.AddKindPairs('VOp3', [
580 ('At', '@'),
581 ('Star', '*'),
582 ])
583
584 # This kind is for Node types that are NOT tokens.
585 spec.AddKind(
586 'Node',
587 [
588 # Arithmetic nodes
589 'PostDPlus',
590 'PostDMinus', # Postfix inc/dec.
591 # Prefix inc/dec use Arith_DPlus/Arith_DMinus.
592 'UnaryPlus',
593 'UnaryMinus', # +1 and -1, to distinguish from infix.
594 # Actually we don't need this because we they
595 # will be under Expr1/Plus vs Expr2/Plus.
596 'NotIn',
597 'IsNot', # For YSH comparisons
598 ])
599
600 # NOTE: Not doing AddKindPairs() here because oil will have a different set
601 # of keywords. It will probably have for/in/while/until/case/if/else/elif,
602 # and then func/proc.
603 spec.AddKind(
604 'KW',
605 [
606 'DLeftBracket',
607 'Bang',
608 'For',
609 'While',
610 'Until',
611 'Do',
612 'Done',
613 'In',
614 'Case',
615 'Esac',
616 'If',
617 'Fi',
618 'Then',
619 'Else',
620 'Elif',
621 'Function',
622 'Time',
623
624 # YSH keywords.
625 'Const',
626 'Var',
627 'SetVar',
628 'SetGlobal',
629 # later: Auto?
630 'Call',
631 'Proc',
632 'Typed',
633 'Func',
634
635 # builtins, NOT keywords: use, fork, wait, etc.
636 # Things that don't affect parsing shouldn't be keywords.
637 ])
638
639 # Unlike bash, we parse control flow statically. They're not
640 # dynamically-resolved builtins.
641 spec.AddKind('ControlFlow', ['Break', 'Continue', 'Return', 'Exit'])
642
643 # Special Kind for lookahead in the lexer. It's never seen by anything else.
644 spec.AddKind('LookAhead', ['FuncParens'])
645
646 # For parsing globs and converting them to regexes.
647 spec.AddKind('Glob', [
648 'LBracket',
649 'RBracket',
650 'Star',
651 'QMark',
652 'Bang',
653 'Caret',
654 'EscapedChar',
655 'BadBackslash',
656 'CleanLiterals',
657 'OtherLiteral',
658 ])
659
660 # For C-escaped strings.
661 spec.AddKind(
662 'Format',
663 [
664 'EscapedPercent',
665 'Percent', # starts another lexer mode
666 'Flag',
667 'Num',
668 'Dot',
669 'Type',
670 'Star',
671 'Time',
672 'Zero',
673 ])
674
675 # For parsing prompt strings like PS1.
676 spec.AddKind('PS', [
677 'Subst',
678 'Octal3',
679 'LBrace',
680 'RBrace',
681 'Literals',
682 'BadBackslash',
683 ])
684
685 spec.AddKind('Range', ['Int', 'Char', 'Dots', 'Other'])
686
687 spec.AddKind(
688 'J8',
689 [
690 'LBracket',
691 'RBracket',
692 'LBrace',
693 'RBrace',
694 'Comma',
695 'Colon',
696 'Null',
697 'Bool',
698 'Int', # Number
699 'Float', # Number
700
701 # High level tokens for "" b'' u''
702 # We don't distinguish them in the parser, because we recognize
703 # strings in the lexer.
704 'String',
705
706 # JSON8 and NIL8
707 'Identifier',
708 'Newline', # J8 Lines only, similar to Op_Newline
709 'Tab', # Reserved for TSV8
710
711 # NIL8 only
712 'LParen',
713 'RParen',
714 #'Symbol',
715 'Operator',
716 ])
717
718 spec.AddKind('ShNumber', ['Dec', 'Hex', 'Oct', 'BaseN'])
719
720
721# Shared between [[ and test/[.
722_UNARY_STR_CHARS = 'zn' # -z -n
723_UNARY_OTHER_CHARS = 'otvR' # -o is overloaded
724_UNARY_PATH_CHARS = 'abcdefghkLprsSuwxOGN' # -a is overloaded
725
726_BINARY_PATH = ['ef', 'nt', 'ot']
727_BINARY_INT = ['eq', 'ne', 'gt', 'ge', 'lt', 'le']
728
729
730def _Dash(strs):
731 # type: (List[str]) -> List[Tuple[str, str]]
732 # Gives a pair of (token name, string to match)
733 return [(s, '-' + s) for s in strs]
734
735
736def AddBoolKinds(spec):
737 # type: (IdSpec) -> None
738 spec.AddBoolKind('BoolUnary', [
739 (bool_arg_type_e.Str, _Dash(list(_UNARY_STR_CHARS))),
740 (bool_arg_type_e.Other, _Dash(list(_UNARY_OTHER_CHARS))),
741 (bool_arg_type_e.Path, _Dash(list(_UNARY_PATH_CHARS))),
742 ])
743
744 Id = spec.id_str2int
745
746 # test --true and test --false have no single letter flags. They need no
747 # lexing.
748 for long_flag in ('true', 'false'):
749 id_name = 'BoolUnary_%s' % long_flag
750 spec._AddId(id_name)
751 spec.AddBoolOp(Id[id_name], bool_arg_type_e.Str)
752
753 spec.AddBoolKind('BoolBinary', [
754 (bool_arg_type_e.Str, [
755 ('GlobEqual', '='),
756 ('GlobDEqual', '=='),
757 ('GlobNEqual', '!='),
758 ('EqualTilde', '=~'),
759 ]),
760 (bool_arg_type_e.Path, _Dash(_BINARY_PATH)),
761 (bool_arg_type_e.Int, _Dash(_BINARY_INT)),
762 ])
763
764 # logical, arity, arg_type
765 spec.AddBoolOp(Id['Op_DAmp'], bool_arg_type_e.Undefined)
766 spec.AddBoolOp(Id['Op_DPipe'], bool_arg_type_e.Undefined)
767 spec.AddBoolOp(Id['KW_Bang'], bool_arg_type_e.Undefined)
768
769 spec.AddBoolOp(Id['Op_Less'], bool_arg_type_e.Str)
770 spec.AddBoolOp(Id['Op_Great'], bool_arg_type_e.Str)
771
772
773def SetupTestBuiltin(
774 id_spec, # type: IdSpec
775 unary_lookup, # type: Dict[str, int]
776 binary_lookup, # type: Dict[str, int]
777 other_lookup, # type: Dict[str, int]
778):
779 # type: (...) -> None
780 """Setup tokens for test/[.
781
782 Similar to _AddBoolKinds above. Differences:
783 - =~ doesn't exist
784 - && -> -a, || -> -o
785 - ( ) -> Op_LParen (they don't appear above)
786 """
787 Id = id_spec.id_str2int
788 Kind = id_spec.kind_str2int
789
790 for letter in _UNARY_STR_CHARS + _UNARY_OTHER_CHARS + _UNARY_PATH_CHARS:
791 id_name = 'BoolUnary_%s' % letter
792 unary_lookup['-' + letter] = Id[id_name]
793
794 for s in _BINARY_PATH + _BINARY_INT:
795 id_name = 'BoolBinary_%s' % s
796 binary_lookup['-' + s] = Id[id_name]
797
798 # Like the [[ definition above, but without globbing and without =~ .
799
800 for id_name, token_str in [('Equal', '='), ('DEqual', '=='),
801 ('NEqual', '!=')]:
802 id_int = id_spec.AddBoolBinaryForBuiltin(id_name, Kind['BoolBinary'])
803
804 binary_lookup[token_str] = id_int
805
806 # Some of these names don't quite match, but it keeps the BoolParser simple.
807 binary_lookup['<'] = Id['Op_Less']
808 binary_lookup['>'] = Id['Op_Great']
809
810 # NOTE: -a and -o overloaded as unary prefix operators BoolUnary_a and
811 # BoolUnary_o. The parser rather than the tokenizer handles this.
812 other_lookup['!'] = Id['KW_Bang'] # like [[ !
813 other_lookup['('] = Id['Op_LParen']
814 other_lookup[')'] = Id['Op_RParen']
815
816 other_lookup[']'] = Id['Arith_RBracket'] # For closing ]