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

423 lines, 213 significant
1#!/usr/bin/env python2
2from __future__ import print_function
3
4from typing import List, Dict, Optional, Tuple, Any
5
6
7class Option(object):
8
9 def __init__(self,
10 index,
11 name,
12 short_flag=None,
13 builtin='shopt',
14 default=False,
15 implemented=True,
16 groups=None):
17 # type: (int, str, str, Optional[str], bool, bool, List[str]) -> None
18 self.index = index
19 self.name = name # e.g. 'errexit'
20 self.short_flag = short_flag # 'e' for -e
21
22 if short_flag:
23 self.builtin = 'set'
24 else:
25 # The 'interactive' option is the only one where builtin is None. It has
26 # a cell but you can't change it. Only the shell can.
27 self.builtin = builtin
28
29 self.default = default # default value is True in some cases
30 self.implemented = implemented
31 self.groups = groups or [] # list of groups
32
33 # for optview
34 self.is_parse = (name.startswith('parse_') or
35 name.startswith('strict_parse_') or
36 name == 'expand_aliases')
37 # interactive() is an accessor
38 self.is_exec = implemented and not self.is_parse
39
40
41class _OptionDef(object):
42 """Description of all shell options.
43
44 Similar to id_kind_def.IdSpec
45 """
46
47 def __init__(self):
48 # type: () -> None
49 self.opts = [] # type: List[Option]
50 self.index = 1 # start with 1
51 self.array_size = -1
52
53 def Add(self, *args, **kwargs):
54 # type: (Any, Any) -> None
55 self.opts.append(Option(self.index, *args, **kwargs))
56 self.index += 1
57
58 def DoneWithImplementedOptions(self):
59 # type: () -> None
60 self.array_size = self.index
61
62
63# Used by builtin
64_OTHER_SET_OPTIONS = [
65 # NOTE: set -i and +i is explicitly disallowed. Only osh -i or +i is valid
66 # https://unix.stackexchange.com/questions/339506/can-an-interactive-shell-become-non-interactive-or-vice-versa
67 ('n', 'noexec'),
68 ('x', 'xtrace'),
69 ('v', 'verbose'), # like xtrace, but prints unevaluated commands
70 ('f', 'noglob'),
71 ('C', 'noclobber'),
72 ('E', 'errtrace'),
73
74 # A no-op for modernish.
75 (None, 'posix'),
76 (None, 'vi'),
77 (None, 'emacs'),
78]
79
80_STRICT_OPTS = [
81 # $a{[@]::} is not allowed, you need ${a[@]::0} or ${a[@]::n}
82 'strict_parse_slice',
83
84 # These are RUNTIME strict options.
85 'strict_argv', # empty argv not allowed
86 'strict_arith', # string to integer conversions, e.g. x=foo; echo $(( x ))
87
88 # No implicit conversions between string and array.
89 # - foo="$@" not allowed because it decays. Should be foo=( "$@" ).
90 # - ${a} not ${a[0]} (not implemented)
91 # sane-array? compare arrays like [[ "$@" == "${a[@]}" ]], which is
92 # incompatible because bash coerces
93 # default: do not allow
94 'strict_array',
95 'strict_control_flow', # break/continue at top level is fatal
96 # 'return $empty' and return "" are NOT accepted
97 'strict_errexit', # errexit can't be disabled in compound commands
98 'strict_nameref', # trap invalid variable names
99 'strict_word_eval', # negative slices, unicode
100 'strict_tilde', # ~nonexistent is an error (like zsh)
101
102 # Not implemented
103 'strict_glob', # glob_.py GlobParser has warnings
104]
105
106# These will break some programs, but the fix should be simple.
107
108# command_sub_errexit makes 'local foo=$(false)' and echo $(false) fail.
109# By default, we have mimic bash's undesirable behavior of ignoring
110# these failures, since ash copied it, and Alpine's abuild relies on it.
111#
112# Note that inherit_errexit is a strict option.
113
114_UPGRADE_RUNTIME_OPTS = [
115 ('simple_word_eval', False), # No splitting; arity isn't data-dependent
116 # Don't reparse program data as globs
117 ('dashglob', True), # do globs return files starting with - ?
118
119 # TODO: Should these be in strict mode?
120 # The logic was that strict_errexit improves your bash programs, but these
121 # would lead you to remove error handling. But the same could be said for
122 # strict_array?
123 ('command_sub_errexit', False), # check after command sub
124 ('process_sub_fail', False), # like pipefail, but for <(sort foo.txt)
125 ('xtrace_rich', False), # Hierarchical trace with PIDs
126 ('xtrace_details', True), # Legacy set -x stuff
127
128 # Whether status 141 in pipelines is turned into 0
129 ('sigpipe_status_ok', False),
130
131 # create ENV at startup; read from it when starting processes
132 ('env_obj', False),
133
134 # Can create closures from loop variables, like JS / C# / Go
135 ('for_loop_frames', False),
136]
137
138# TODO: Add strict_arg_parse? For example, 'trap 1 2 3' shouldn't be
139# valid, because it has an extra argument. Builtins are inconsistent about
140# checking this.
141
142_YSH_RUNTIME_OPTS = [
143 ('no_exported', False), # don't initialize or use exported variables
144 ('no_init_globals', False), # don't initialize PWD, COMP_WORDBREAKS, etc.
145 ('simple_echo', False), # echo takes 0 or 1 arguments
146 ('simple_eval_builtin', False), # eval takes exactly 1 argument
147
148 # only file tests (no strings), remove [, status 2
149 ('simple_test_builtin', False),
150
151 # TODO: simple_trap
152
153 # Turn aliases off so we can statically parse. bash has it off
154 # non-interactively, sothis shouldn't break much.
155 ('expand_aliases', True),
156]
157
158# Stuff that doesn't break too many programs.
159_UPGRADE_PARSE_OPTS = [
160 'parse_at', # @array, @[expr]
161 'parse_proc', # proc p { ... }
162 'parse_func', # func f(x) { ... }
163 'parse_brace', # cd /bin { ... }
164 'parse_bracket', # assert [42 === x]
165
166 # bare assignment 'x = 42' is allowed in Hay { } blocks, but disallowed
167 # everywhere else. It's not a command 'x' with arg '='.
168 'parse_equals',
169 'parse_paren', # if (x > 0) ...
170 'parse_ysh_string', # r'' u'' b'' and multi-line versions
171 'parse_triple_quote', # for ''' and """
172]
173
174# Extra stuff that breaks too many programs.
175_YSH_PARSE_OPTS = [
176 ('parse_at_all', False), # @ starting any word, e.g. @[] @{} @@ @_ @-
177
178 # Legacy syntax that is removed. These options are distinct from strict_*
179 # because they don't help you avoid bugs in bash programs. They just makes
180 # the language more consistent.
181 ('parse_backslash', True),
182 ('parse_backticks', True),
183 ('parse_dollar', True),
184 ('parse_ignored', True),
185 ('parse_sh_arith', True), # disallow all shell arithmetic, $(( )) etc.
186 ('parse_dparen', True), # disallow bash's ((
187 ('parse_dbracket', True), # disallow bash's [[
188 ('parse_bare_word', True), # 'case bare' and 'for x in bare'
189]
190
191# No-ops for bash compatibility
192_NO_OPS = [
193 # Handled one by one
194 'progcomp',
195 'histappend', # stubbed out for issue #218
196 'hostcomplete', # complete words with '@' ?
197 'cmdhist', # multi-line commands in history
198
199 # Copied from https://www.gnu.org/software/bash/manual/bash.txt
200 # except 'compat*' because they were deemed too ugly
201 'assoc_expand_once',
202 'autocd',
203 'cdable_vars',
204 'cdspell',
205 'checkhash',
206 'checkjobs',
207 'checkwinsize',
208 'complete_fullquote', # Set by default
209 # If set, Bash quotes all shell metacharacters in filenames and
210 # directory names when performing completion. If not set, Bash
211 # removes metacharacters such as the dollar sign from the set of
212 # characters that will be quoted in completed filenames when
213 # these metacharacters appear in shell variable references in
214 # words to be completed. This means that dollar signs in
215 # variable names that expand to directories will not be quoted;
216 # however, any dollar signs appearing in filenames will not be
217 # quoted, either. This is active only when bash is using
218 # backslashes to quote completed filenames. This variable is
219 # set by default, which is the default Bash behavior in versions
220 # through 4.2.
221 'direxpand',
222 'dirspell',
223 'execfail',
224 'extquote',
225 'force_fignore',
226 'globasciiranges',
227 'globstar', # TODO: implement **
228 'gnu_errfmt',
229 'histreedit',
230 'histverify',
231 'huponexit',
232 'interactive_comments',
233 'lithist',
234 'localvar_inherit',
235 'localvar_unset',
236 'login_shell',
237 'mailwarn',
238 'no_empty_cmd_completion',
239 'nocaseglob',
240 'progcomp_alias',
241 'promptvars',
242 'restricted_shell',
243 'shift_verbose',
244 'sourcepath',
245 'xpg_echo',
246]
247
248
249def _Init(opt_def):
250 # type: (_OptionDef) -> None
251
252 opt_def.Add('errexit',
253 short_flag='e',
254 builtin='set',
255 groups=['ysh:upgrade', 'ysh:all'])
256 opt_def.Add('nounset',
257 short_flag='u',
258 builtin='set',
259 groups=['ysh:upgrade', 'ysh:all'])
260 opt_def.Add('pipefail', builtin='set', groups=['ysh:upgrade', 'ysh:all'])
261
262 opt_def.Add('inherit_errexit', groups=['ysh:upgrade', 'ysh:all'])
263 # Hm is this subsumed by simple_word_eval?
264 opt_def.Add('nullglob', groups=['ysh:upgrade', 'ysh:all'])
265 opt_def.Add('verbose_errexit', groups=['ysh:upgrade', 'ysh:all'])
266
267 # set -o noclobber, etc.
268 for short_flag, name in _OTHER_SET_OPTIONS:
269 opt_def.Add(name, short_flag=short_flag, builtin='set')
270
271 # The only one where builtin=None. Only the shell can change it.
272 opt_def.Add('interactive', builtin=None)
273
274 # bash --norc -c 'set -o' shows this is on by default
275 opt_def.Add('hashall', short_flag='h', builtin='set', default=True)
276
277 # This option is always on
278 opt_def.Add('lastpipe', default=True)
279
280 #
281 # shopt
282 # (bash uses $BASHOPTS rather than $SHELLOPTS)
283 #
284
285 # shopt options that aren't in any groups.
286 opt_def.Add('failglob')
287 opt_def.Add('extglob')
288 opt_def.Add('nocasematch')
289 opt_def.Add('dotglob')
290
291 opt_def.Add('extdebug') # for task files
292
293 # recursive parsing and evaluation - for compatibility, ble.sh, etc.
294 opt_def.Add('eval_unsafe_arith')
295
296 opt_def.Add('ignore_flags_not_impl')
297 opt_def.Add('ignore_shopt_not_impl')
298
299 # For implementing strict_errexit
300 # TODO: could be _no_command_sub / _no_process_sub, if we had to discourage
301 # "default True" options
302 opt_def.Add('_allow_command_sub', default=True)
303 opt_def.Add('_allow_process_sub', default=True)
304
305 # For implementing 'proc'
306 opt_def.Add('dynamic_scope', default=True)
307
308 # On in interactive shell
309 opt_def.Add('redefine_const', default=False)
310 opt_def.Add('redefine_source', default=False)
311
312 # For disabling strict_errexit while running traps. Because we run in the
313 # main loop, the value can be "off". Prefix with _ because it's undocumented
314 # and users shouldn't fiddle with it. We need a stack so this is a
315 # convenient place.
316 opt_def.Add('_running_trap')
317 opt_def.Add('_running_hay')
318
319 # For fixing lastpipe / job control / DEBUG trap interaction
320 opt_def.Add('_no_debug_trap')
321 # To implement ERR trap semantics - it's only run for the WHOLE pipeline,
322 # not each part (even the last part)
323 opt_def.Add('_no_err_trap')
324
325 # shopt -s strict_arith, etc.
326 for name in _STRICT_OPTS:
327 opt_def.Add(name, groups=['strict:all', 'ysh:all'])
328
329 #
330 # Options that enable YSH features
331 #
332
333 #opt_def.Add('no_exported') # TODO: move this
334 for name in _UPGRADE_PARSE_OPTS:
335 opt_def.Add(name, groups=['ysh:upgrade', 'ysh:all'])
336 # shopt -s simple_word_eval, etc.
337 for name, default in _UPGRADE_RUNTIME_OPTS:
338 opt_def.Add(name, default=default, groups=['ysh:upgrade', 'ysh:all'])
339
340 for name, default in _YSH_PARSE_OPTS:
341 opt_def.Add(name, default=default, groups=['ysh:all'])
342 for name, default in _YSH_RUNTIME_OPTS:
343 opt_def.Add(name, default=default, groups=['ysh:all'])
344
345 opt_def.DoneWithImplementedOptions()
346
347 # NO_OPS
348
349 # Stubs for shopt -s xpg_echo, etc.
350 for name in _NO_OPS:
351 opt_def.Add(name, implemented=False)
352
353
354def All():
355 # type: () -> List[Option]
356 """Return a list of options with metadata.
357
358 - Used by osh/builtin_pure.py to construct the arg spec.
359 - Used by frontend/lexer_gen.py to construct the lexer/matcher
360 """
361 return _OPTION_DEF.opts
362
363
364def ArraySize():
365 # type: () -> int
366 """Unused now, since we use opt_num::ARRAY_SIZE.
367
368 We could get rid of unimplemented options and shrink the array.
369 """
370 return _OPTION_DEF.array_size
371
372
373def OptionDict():
374 # type: () -> Dict[str, Tuple[int, bool]]
375 """Implemented options.
376
377 For the slow path in frontend/consts.py
378 """
379 d = {}
380 for opt in _OPTION_DEF.opts:
381 d[opt.name] = (opt.index, opt.implemented)
382 return d
383
384
385def ParseOptNames():
386 # type: () -> List[str]
387 """Used by core/optview*.py."""
388 return [opt.name for opt in _OPTION_DEF.opts if opt.is_parse]
389
390
391def ExecOptNames():
392 # type: () -> List[str]
393 """Used by core/optview*.py."""
394 return [opt.name for opt in _OPTION_DEF.opts if opt.is_exec]
395
396
397_OPTION_DEF = _OptionDef()
398
399_Init(_OPTION_DEF)
400
401# Sort by name because we print options.
402# TODO: for MEMBERSHIP queries, we could sort by the most common? errexit
403# first?
404_SORTED = sorted(_OPTION_DEF.opts, key=lambda opt: opt.name)
405
406PARSE_OPTION_NUMS = [opt.index for opt in _SORTED if opt.is_parse]
407
408# Sorted because 'shopt -o -p' should be sorted, etc.
409VISIBLE_SHOPT_NUMS = [
410 opt.index for opt in _SORTED if opt.builtin == 'shopt' and opt.implemented
411]
412
413YSH_UPGRADE = [opt.index for opt in _SORTED if 'ysh:upgrade' in opt.groups]
414YSH_ALL = [opt.index for opt in _SORTED if 'ysh:all' in opt.groups]
415STRICT_ALL = [opt.index for opt in _SORTED if 'strict:all' in opt.groups]
416DEFAULT_TRUE = [opt.index for opt in _SORTED if opt.default]
417#print([opt.name for opt in _SORTED if opt.default])
418
419META_OPTIONS = ['strict:all', 'ysh:upgrade',
420 'ysh:all'] # Passed to flag parser
421
422# For printing option names to stdout. Wrapped by frontend/consts.
423OPTION_NAMES = dict((opt.index, opt.name) for opt in _SORTED)