myshell-py 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
myshell/expand.py ADDED
@@ -0,0 +1,704 @@
1
+ """Expansion: variables, $(...), word splitting, globbing and tilde."""
2
+ import glob
3
+ import os
4
+ import re
5
+ import sys
6
+ from typing import List, Optional, Tuple
7
+
8
+ from .paths import expand_user
9
+ from . import compat
10
+ from .arith import evaluate
11
+ from .errors import ShellError, ShellExit
12
+ from .lexer import WORD, Token, find_matching_brace, find_matching_paren, read_backticks
13
+ from .state import ShellState
14
+
15
+
16
+ VAR_RE = re.compile(r"\$(\?|\$|#|@|\*|[0-9]|[A-Za-z_][A-Za-z0-9_]*)")
17
+ PARAM_RE = re.compile(r"([A-Za-z_][A-Za-z0-9_]*|[0-9]+|[?$#@*])(.*)", re.DOTALL)
18
+ SPECIAL_NAMES = ("?", "$", "#", "@", "*")
19
+ ASSIGN_RE = re.compile(r"([A-Za-z_][A-Za-z0-9_]*)=(.*)", re.DOTALL)
20
+
21
+
22
+ def portable_substitution(text: str, state: ShellState) -> str:
23
+ """No fork here (Windows). Run the text in this process with output sent to a temp file.
24
+ The folder, the variables and the environment are restored afterwards."""
25
+ import tempfile
26
+ sys.stdout.flush()
27
+ sys.stderr.flush()
28
+ saved_out = sys.stdout
29
+ saved_cwd = os.getcwd()
30
+ saved_env = dict(os.environ)
31
+ saved_vars = dict(state.variables)
32
+ saved_pos = list(state.positional)
33
+ saved_status = state.last_status
34
+ with tempfile.TemporaryFile("w+", encoding="utf-8", errors="replace") as f:
35
+ sys.stdout = f
36
+ try:
37
+ state.execute(text)
38
+ except ShellExit:
39
+ pass
40
+ except ShellError as e:
41
+ print(e, file=sys.stderr)
42
+ finally:
43
+ f.flush()
44
+ sys.stdout = saved_out
45
+ os.chdir(saved_cwd)
46
+ os.environ.clear()
47
+ os.environ.update(saved_env)
48
+ state.variables.clear()
49
+ state.variables.update(saved_vars)
50
+ state.positional = saved_pos
51
+ f.seek(0)
52
+ output = f.read()
53
+ state.last_status = saved_status
54
+ return output.rstrip("\n")
55
+
56
+
57
+ def command_substitution(text: str, state: ShellState) -> str:
58
+ """Run text in a subshell and return its output without trailing newlines.
59
+ The subshell is a forked copy of this shell, so aliases, builtins and
60
+ variables work. Changes it makes (cd, exports) do not reach the parent."""
61
+ if not compat.HAS_FORK:
62
+ return portable_substitution(text, state)
63
+ sys.stdout.flush()
64
+ sys.stderr.flush()
65
+ read_fd, write_fd = os.pipe()
66
+ pid = os.fork()
67
+ if pid == 0:
68
+ status = 1
69
+ try:
70
+ os.close(read_fd)
71
+ os.dup2(write_fd, 1)
72
+ os.close(write_fd)
73
+ # Fresh file objects, so output reaches fd 1 even if sys.stdout was replaced.
74
+ sys.stdout = os.fdopen(1, "w", closefd=False)
75
+ sys.stderr = os.fdopen(2, "w", buffering=1, closefd=False)
76
+ state.jobs.interactive = False # a subshell never takes over the terminal
77
+ status = state.execute(text)
78
+ except ShellExit as e:
79
+ status = e.code
80
+ except ShellError as e:
81
+ print(e, file=sys.stderr)
82
+ status = 2
83
+ except BaseException:
84
+ status = 1
85
+ finally:
86
+ try:
87
+ sys.stdout.flush()
88
+ sys.stderr.flush()
89
+ except Exception:
90
+ pass
91
+ os._exit(status & 0xFF)
92
+ os.close(write_fd)
93
+ chunks: List[bytes] = []
94
+ try:
95
+ while True:
96
+ data = os.read(read_fd, 65536)
97
+ if not data:
98
+ break
99
+ chunks.append(data)
100
+ finally:
101
+ os.close(read_fd)
102
+ try:
103
+ os.waitpid(pid, 0)
104
+ except ChildProcessError:
105
+ pass
106
+ return b"".join(chunks).decode(errors="replace").rstrip("\n")
107
+
108
+
109
+ def fail(state: ShellState, message: str) -> ShellError:
110
+ """An expansion error. A script stops at it, as in other shells. The prompt carries on."""
111
+ if not state.jobs.interactive and not state.keep_going:
112
+ print(message, file=sys.stderr)
113
+ raise ShellExit(1)
114
+ return ShellError(message)
115
+
116
+
117
+ def lookup(name: str, state: ShellState) -> Optional[str]:
118
+ """The value of a variable or special parameter. None when it is not set."""
119
+ if name == "?":
120
+ return str(state.last_status)
121
+ if name == "$":
122
+ return str(os.getpid())
123
+ if name == "#":
124
+ return str(len(state.positional))
125
+ if name in ("@", "*"):
126
+ return " ".join(state.positional)
127
+ if name.isdigit():
128
+ n = int(name)
129
+ if n == 0:
130
+ return state.script_name
131
+ return state.positional[n - 1] if n <= len(state.positional) else None
132
+ return state.get_variable(name)
133
+
134
+
135
+ def variable_value(name: str, state: ShellState) -> str:
136
+ value = lookup(name, state)
137
+ if value is None:
138
+ if "nounset" in state.options and name not in SPECIAL_NAMES and not name.isdigit():
139
+ raise fail(state, f"{name}: unbound variable")
140
+ return ""
141
+ return value
142
+
143
+
144
+ # --- glob patterns used by ${X#pat}, ${X/pat/new} and case ---
145
+ def glob_to_regex(pattern: str) -> str:
146
+ out = []
147
+ i, n = 0, len(pattern)
148
+ while i < n:
149
+ c = pattern[i]
150
+ i += 1
151
+ if c == "*":
152
+ out.append(".*")
153
+ elif c == "?":
154
+ out.append(".")
155
+ elif c == "[":
156
+ j = i
157
+ if j < n and pattern[j] in "!^":
158
+ j += 1
159
+ if j < n and pattern[j] == "]":
160
+ j += 1
161
+ while j < n and pattern[j] != "]":
162
+ j += 1
163
+ if j >= n:
164
+ out.append(re.escape(c))
165
+ else:
166
+ body = pattern[i:j]
167
+ if body[:1] in ("!", "^"):
168
+ body = "^" + body[1:]
169
+ out.append("[" + body.replace("\\", "\\\\") + "]")
170
+ i = j + 1
171
+ else:
172
+ out.append(re.escape(c))
173
+ return "".join(out)
174
+
175
+
176
+ def glob_match(pattern: str, text: str) -> bool:
177
+ return re.fullmatch(glob_to_regex(pattern), text, re.DOTALL) is not None
178
+
179
+
180
+ def expand_param_word(text: str, state: ShellState) -> str:
181
+ """Expand the word inside ${X:-word}: quotes, backslashes and $ expansions. No splitting."""
182
+ out: List[str] = []
183
+ i = 0
184
+ while i < len(text):
185
+ c = text[i]
186
+ if c == "'":
187
+ end = text.find("'", i + 1)
188
+ end = len(text) if end < 0 else end
189
+ out.append(text[i + 1:end])
190
+ i = end + 1
191
+ elif c == '"':
192
+ end = i + 1
193
+ while end < len(text) and text[end] != '"':
194
+ end += 2 if text[end] == "\\" else 1
195
+ out.append(expand_vars(text[i + 1:end], state))
196
+ i = end + 1
197
+ elif c == "\\" and i + 1 < len(text):
198
+ out.append(text[i + 1])
199
+ i += 2
200
+ elif c == "$":
201
+ found = expand_dollar(text, i, state)
202
+ if found is None:
203
+ out.append(c)
204
+ i += 1
205
+ else:
206
+ out.append(found[0])
207
+ i = found[1]
208
+ else:
209
+ out.append(c)
210
+ i += 1
211
+ return "".join(out)
212
+
213
+
214
+ def expand_param_pattern(text: str, state: ShellState) -> str:
215
+ """Like expand_param_word, but quoted characters stay literal inside a glob pattern."""
216
+ out: List[str] = []
217
+ i = 0
218
+ while i < len(text):
219
+ c = text[i]
220
+ if c == "'":
221
+ end = text.find("'", i + 1)
222
+ end = len(text) if end < 0 else end
223
+ out.append(glob.escape(text[i + 1:end]))
224
+ i = end + 1
225
+ elif c == '"':
226
+ end = i + 1
227
+ while end < len(text) and text[end] != '"':
228
+ end += 2 if text[end] == "\\" else 1
229
+ out.append(glob.escape(expand_vars(text[i + 1:end], state)))
230
+ i = end + 1
231
+ elif c == "\\" and i + 1 < len(text):
232
+ out.append(glob.escape(text[i + 1]))
233
+ i += 2
234
+ elif c == "$":
235
+ found = expand_dollar(text, i, state)
236
+ if found is None:
237
+ out.append(c)
238
+ i += 1
239
+ else:
240
+ out.append(found[0])
241
+ i = found[1]
242
+ else:
243
+ out.append(c)
244
+ i += 1
245
+ return "".join(out)
246
+
247
+
248
+ def split_unescaped(text: str, sep: str) -> Tuple[str, Optional[str]]:
249
+ """Split text at the first sep that is not escaped or inside quotes or ${}."""
250
+ depth = 0
251
+ quote = None
252
+ i = 0
253
+ while i < len(text):
254
+ c = text[i]
255
+ if quote:
256
+ if c == "\\" and quote == '"':
257
+ i += 1
258
+ elif c == quote:
259
+ quote = None
260
+ elif c == "\\":
261
+ i += 1
262
+ elif c in "'\"":
263
+ quote = c
264
+ elif c == "$" and text.startswith("${", i):
265
+ depth += 1
266
+ i += 1
267
+ elif c == "}" and depth:
268
+ depth -= 1
269
+ elif c == sep and depth == 0:
270
+ return text[:i], text[i + 1:]
271
+ i += 1
272
+ return text, None
273
+
274
+
275
+ def param_expansion(body: str, state: ShellState) -> str:
276
+ """The text inside ${...}: ${X}, ${#X}, ${X:-w}, ${X:=w}, ${X:?w}, ${X:+w},
277
+ ${X#p} ${X##p} ${X%p} ${X%%p}, ${X/p/r} ${X//p/r}, ${X:off:len}, ${X^^} ${X,,}."""
278
+ if body == "#":
279
+ return str(len(state.positional))
280
+ if body.startswith("#") and len(body) > 1 and PARAM_RE.fullmatch(body[1:]):
281
+ name = body[1:]
282
+ if name in ("@", "*"):
283
+ return str(len(state.positional))
284
+ return str(len(variable_value(name, state)))
285
+ m = PARAM_RE.fullmatch(body)
286
+ if not m:
287
+ raise ShellError(f"${{{body}}}: bad substitution")
288
+ name, op = m.group(1), m.group(2)
289
+ if not op:
290
+ return variable_value(name, state)
291
+ raw = lookup(name, state)
292
+ value = raw if raw is not None else ""
293
+ colon = op.startswith(":") and len(op) > 1 and op[1] in "-=?+"
294
+ if colon or op[0] in "-=?+":
295
+ kind = op[1] if colon else op[0]
296
+ word = op[2:] if colon else op[1:]
297
+ missing = raw is None or (colon and raw == "")
298
+ if kind == "-":
299
+ return expand_param_word(word, state) if missing else value
300
+ if kind == "=":
301
+ if not missing:
302
+ return value
303
+ if name in SPECIAL_NAMES or name.isdigit():
304
+ raise ShellError(f"${name}: cannot assign in this way")
305
+ new = expand_param_word(word, state)
306
+ state.set_variable(name, new)
307
+ return new
308
+ if kind == "?":
309
+ if missing:
310
+ message = expand_param_word(word, state) or "parameter null or not set"
311
+ raise fail(state, f"{name}: {message}")
312
+ return value
313
+ return "" if missing else expand_param_word(word, state) # "+"
314
+ if "nounset" in state.options and raw is None and name not in SPECIAL_NAMES:
315
+ raise fail(state, f"{name}: unbound variable")
316
+ if op[0] in "#%":
317
+ longest = op.startswith(op[0] * 2)
318
+ pattern = expand_param_pattern(op[2 if longest else 1:], state)
319
+ if op[0] == "#":
320
+ sizes = range(len(value), -1, -1) if longest else range(0, len(value) + 1)
321
+ for k in sizes:
322
+ if glob_match(pattern, value[:k]):
323
+ return value[k:]
324
+ else:
325
+ starts = range(0, len(value) + 1) if longest else range(len(value), -1, -1)
326
+ for k in starts:
327
+ if glob_match(pattern, value[k:]):
328
+ return value[:k]
329
+ return value
330
+ if op[0] == "/":
331
+ mode = ""
332
+ rest = op[1:]
333
+ if rest[:1] in ("/", "#", "%"):
334
+ mode, rest = rest[0], rest[1:]
335
+ pat_text, rep_text = split_unescaped(rest, "/")
336
+ pattern = expand_param_pattern(pat_text, state)
337
+ replacement = expand_param_word(rep_text or "", state)
338
+ if pattern == "":
339
+ return value
340
+ rx = glob_to_regex(pattern)
341
+ if mode == "#":
342
+ rx = "^" + rx
343
+ elif mode == "%":
344
+ rx = rx + "$"
345
+ count = 0 if mode == "/" else 1
346
+ return re.sub(rx, lambda _: replacement, value, count=count, flags=re.DOTALL)
347
+ if op[0] == ":":
348
+ off_text, len_text = split_unescaped(op[1:], ":")
349
+ offset = int(arithmetic(off_text.strip() or "0", state))
350
+ if offset < 0:
351
+ offset = max(0, len(value) + offset)
352
+ if len_text is None:
353
+ return value[offset:]
354
+ length = int(arithmetic(len_text.strip() or "0", state))
355
+ return value[offset:offset + length] if length >= 0 else value[offset:length]
356
+ if op in ("^^", "^", ",,", ","):
357
+ if op == "^^":
358
+ return value.upper()
359
+ if op == ",,":
360
+ return value.lower()
361
+ return (value[:1].upper() if op == "^" else value[:1].lower()) + value[1:]
362
+ raise ShellError(f"${{{body}}}: bad substitution")
363
+
364
+
365
+ def arithmetic(expr: str, state: ShellState) -> str:
366
+ """Expand $VAR and $(...) inside expr, then evaluate it as integer math."""
367
+ expr = expand_vars(expr, state)
368
+ return str(evaluate(expr, state.get_variable, state.set_variable))
369
+
370
+
371
+ def expand_dollar(text: str, i: int, state: ShellState) -> Optional[Tuple[str, int]]:
372
+ """text[i] is '$'. If an expansion starts here, return (value, index after it).
373
+ Handles $((...)), $(...), $VAR, ${VAR}, $? and $$. A lone '$' returns None."""
374
+ if text.startswith("$(", i):
375
+ end = find_matching_paren(text, i + 1)
376
+ # $(( ... )) is math when the inner pair closes right before the outer one.
377
+ if text.startswith("$((", i) and find_matching_paren(text, i + 2) == end - 1:
378
+ return arithmetic(text[i + 3:end - 1], state), end + 1
379
+ return command_substitution(text[i + 2:end], state), end + 1
380
+ if text.startswith("${", i):
381
+ end = find_matching_brace(text, i + 1)
382
+ return param_expansion(text[i + 2:end], state), end + 1
383
+ m = VAR_RE.match(text, i)
384
+ if m:
385
+ return variable_value(m.group(1), state), m.end()
386
+ return None
387
+
388
+
389
+ def expand_segments(text: str, state: ShellState) -> List[Tuple[str, bool]]:
390
+ """Expand $VAR, $(...) and $((...)) in text. Returns (string, came_from_expansion) pieces."""
391
+ segments: List[Tuple[str, bool]] = []
392
+ literal = ""
393
+ i = 0
394
+ while i < len(text):
395
+ if text[i] == "$":
396
+ found = expand_dollar(text, i, state)
397
+ if found is not None:
398
+ value, i = found
399
+ if literal:
400
+ segments.append((literal, False))
401
+ literal = ""
402
+ segments.append((value, True))
403
+ continue
404
+ literal += text[i]
405
+ i += 1
406
+ if literal:
407
+ segments.append((literal, False))
408
+ return segments
409
+
410
+
411
+ def expand_heredoc(body: str, state: ShellState) -> str:
412
+ """Expand the body of an unquoted here-document. Quotes stay literal.
413
+ A backslash before $, ` or \\ removes the backslash. Backslash-newline joins lines."""
414
+ out: List[str] = []
415
+ i = 0
416
+ while i < len(body):
417
+ c = body[i]
418
+ if c == "\\" and i + 1 < len(body) and body[i + 1] in "$`\\":
419
+ out.append(body[i + 1])
420
+ i += 2
421
+ elif c == "\\" and body.startswith("\\\n", i):
422
+ i += 2
423
+ elif c == "$":
424
+ found = expand_dollar(body, i, state)
425
+ if found is None:
426
+ out.append(c)
427
+ i += 1
428
+ else:
429
+ out.append(found[0])
430
+ i = found[1]
431
+ elif c == "`":
432
+ inner, end = read_backticks(body, i)
433
+ out.append(command_substitution(inner, state))
434
+ i = end + 1
435
+ else:
436
+ out.append(c)
437
+ i += 1
438
+ return "".join(out)
439
+
440
+
441
+ def expand_vars(text: str, state: ShellState) -> str:
442
+ """Expand text that is inside double quotes. The result is never split."""
443
+ return "".join(seg for seg, _ in expand_segments(text, state))
444
+
445
+
446
+ def has_glob_chars(text: str) -> bool:
447
+ return any(ch in text for ch in "*?[")
448
+
449
+
450
+ class _Fields:
451
+ """Collects the words one token expands to."""
452
+
453
+ def __init__(self):
454
+ self.done: List[Tuple[str, str, bool]] = [] # (value, glob pattern, has_glob)
455
+ self._reset()
456
+
457
+ def _reset(self) -> None:
458
+ self.value = ""
459
+ self.pattern = ""
460
+ self.has_glob = False
461
+ self.present = False # true once a quoted part is added, even an empty one
462
+
463
+ def add(self, text: str, pattern: str, has_glob: bool = False, quoted: bool = False) -> None:
464
+ self.value += text
465
+ self.pattern += pattern
466
+ self.has_glob = self.has_glob or has_glob
467
+ if quoted:
468
+ self.present = True
469
+
470
+ def end_field(self) -> None:
471
+ if self.value or self.present: # an empty unquoted field disappears
472
+ self.done.append((self.value, self.pattern, self.has_glob))
473
+ self._reset()
474
+
475
+
476
+ # --- brace expansion: {a,b} and {1..5} ---
477
+ Cell = Tuple[str, str, bool] # (text, mode, protected). Plain text is one character per cell.
478
+ RANGE_NUM = re.compile(r"(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?")
479
+ RANGE_CHAR = re.compile(r"([A-Za-z])\.\.([A-Za-z])(?:\.\.(-?\d+))?")
480
+ MAX_BRACE_WORDS = 20000
481
+
482
+
483
+ def token_cells(tok: Token) -> List[Cell]:
484
+ cells: List[Cell] = []
485
+ for text, mode in tok.parts:
486
+ if mode != "plain":
487
+ cells.append((text, mode, True))
488
+ continue
489
+ protected_until = -1
490
+ for i, ch in enumerate(text):
491
+ if i > protected_until and ch == "$" and text[i + 1:i + 2] in ("{", "("):
492
+ try:
493
+ if text[i + 1] == "{":
494
+ protected_until = find_matching_brace(text, i + 1)
495
+ else:
496
+ protected_until = find_matching_paren(text, i + 1)
497
+ except ShellError:
498
+ protected_until = len(text)
499
+ cells.append((ch, "plain", i <= protected_until))
500
+ return cells
501
+
502
+
503
+ def cells_token(cells: List[Cell]) -> Token:
504
+ parts: List[Tuple[str, str]] = []
505
+ for text, mode, _ in cells:
506
+ if parts and parts[-1][1] == mode == "plain":
507
+ parts[-1] = (parts[-1][0] + text, mode)
508
+ else:
509
+ parts.append((text, mode))
510
+ return Token(WORD, parts)
511
+
512
+
513
+ def is_brace(cell: Cell, ch: str) -> bool:
514
+ return cell[1] == "plain" and not cell[2] and cell[0] == ch
515
+
516
+
517
+ def matching_brace(cells: List[Cell], start: int) -> Optional[int]:
518
+ depth = 0
519
+ for j in range(start, len(cells)):
520
+ if is_brace(cells[j], "{"):
521
+ depth += 1
522
+ elif is_brace(cells[j], "}"):
523
+ depth -= 1
524
+ if depth == 0:
525
+ return j
526
+ return None
527
+
528
+
529
+ def split_commas(cells: List[Cell]) -> List[List[Cell]]:
530
+ parts: List[List[Cell]] = [[]]
531
+ depth = 0
532
+ for c in cells:
533
+ if is_brace(c, "{"):
534
+ depth += 1
535
+ elif is_brace(c, "}"):
536
+ depth -= 1
537
+ if depth == 0 and is_brace(c, ","):
538
+ parts.append([])
539
+ else:
540
+ parts[-1].append(c)
541
+ return parts
542
+
543
+
544
+ def range_values(inner: List[Cell]) -> Optional[List[str]]:
545
+ if any(c[1] != "plain" for c in inner):
546
+ return None
547
+ text = "".join(c[0] for c in inner)
548
+ m = RANGE_NUM.fullmatch(text)
549
+ if m:
550
+ a, b = int(m.group(1)), int(m.group(2))
551
+ step = abs(int(m.group(3))) if m.group(3) else 1
552
+ if step == 0:
553
+ return None
554
+ width = 0
555
+ for end in (m.group(1), m.group(2)):
556
+ digits = end.lstrip("-")
557
+ if len(digits) > 1 and digits.startswith("0"):
558
+ width = max(width, len(end))
559
+ values = range(a, b + 1, step) if a <= b else range(a, b - 1, -step)
560
+ if len(values) > MAX_BRACE_WORDS:
561
+ return None
562
+ return [str(v).zfill(width) if width else str(v) for v in values]
563
+ m = RANGE_CHAR.fullmatch(text)
564
+ if m:
565
+ a, b = ord(m.group(1)), ord(m.group(2))
566
+ step = abs(int(m.group(3))) if m.group(3) else 1
567
+ if step == 0:
568
+ return None
569
+ values = range(a, b + 1, step) if a <= b else range(a, b - 1, -step)
570
+ return [chr(v) for v in values]
571
+ return None
572
+
573
+
574
+ def expand_cells(cells: List[Cell]) -> List[List[Cell]]:
575
+ for i, cell in enumerate(cells):
576
+ if not is_brace(cell, "{"):
577
+ continue
578
+ j = matching_brace(cells, i)
579
+ if j is None:
580
+ continue
581
+ inner = cells[i + 1:j]
582
+ alternatives = split_commas(inner)
583
+ if len(alternatives) > 1:
584
+ pieces = alternatives
585
+ else:
586
+ values = range_values(inner)
587
+ if values is None:
588
+ continue
589
+ pieces = [[(ch, "plain", False) for ch in v] for v in values]
590
+ result: List[List[Cell]] = []
591
+ for piece in pieces:
592
+ result.extend(expand_cells(cells[:i] + piece + cells[j + 1:]))
593
+ if len(result) > MAX_BRACE_WORDS:
594
+ raise ShellError("brace expansion: too many words")
595
+ return result
596
+ return [cells]
597
+
598
+
599
+ def brace_expand(tok: Token) -> List[Token]:
600
+ """{a,b,c} and {1..5} turn one word into several. Quoted braces stay literal."""
601
+ if not any(mode == "plain" and "{" in text for text, mode in tok.parts):
602
+ return [tok]
603
+ return [cells_token(c) for c in expand_cells(token_cells(tok))]
604
+
605
+
606
+ def add_double_quoted(text: str, state: ShellState, fields: "_Fields") -> None:
607
+ """Text inside double quotes. "$@" becomes one word per positional parameter."""
608
+ pieces = re.split(r"(\$@|\$\{@\})", text)
609
+ if len(pieces) == 1:
610
+ t = expand_vars(text, state)
611
+ fields.add(t, glob.escape(t), quoted=True)
612
+ return
613
+ for k, piece in enumerate(pieces):
614
+ if k % 2 == 0:
615
+ t = expand_vars(piece, state)
616
+ fields.add(t, glob.escape(t), quoted=bool(t))
617
+ else:
618
+ for j, value in enumerate(state.positional):
619
+ if j:
620
+ fields.end_field()
621
+ fields.add(value, glob.escape(value), quoted=True)
622
+
623
+
624
+ def expand_word(tok: Token, state: ShellState, globbing: bool = True,
625
+ splitting: bool = True, braces: bool = True) -> List[str]:
626
+ """Expand one word token into zero or more strings.
627
+ Braces expand first. Unquoted $VAR and $(...) results split on whitespace and may
628
+ match files. Quoted text and literal text never split."""
629
+ if braces:
630
+ words = brace_expand(tok)
631
+ if len(words) != 1 or words[0] is not tok:
632
+ result: List[str] = []
633
+ for w in words:
634
+ result.extend(expand_word(w, state, globbing, splitting, braces=False))
635
+ return result
636
+ fields = _Fields()
637
+ for idx, (text, mode) in enumerate(tok.parts):
638
+ if mode == "single":
639
+ fields.add(text, glob.escape(text), quoted=True)
640
+ elif mode == "double":
641
+ add_double_quoted(text, state, fields)
642
+ else:
643
+ if idx == 0:
644
+ text = expand_user(text)
645
+ for seg, from_expansion in expand_segments(text, state):
646
+ if from_expansion and splitting:
647
+ pieces = re.split(r"(\s+)", seg) # odd positions hold the whitespace
648
+ for k, piece in enumerate(pieces):
649
+ if k % 2:
650
+ fields.end_field()
651
+ elif piece:
652
+ fields.add(piece, piece, globbing and has_glob_chars(piece))
653
+ else:
654
+ fields.add(seg, seg, globbing and has_glob_chars(seg))
655
+ fields.end_field()
656
+
657
+ result: List[str] = []
658
+ for value, pattern, has_glob in fields.done:
659
+ if has_glob:
660
+ matches = sorted(glob.glob(pattern))
661
+ if matches:
662
+ result.extend(matches)
663
+ continue
664
+ result.append(value)
665
+ return result
666
+
667
+
668
+ def expand_tokens(tokens: List[Token], state: ShellState) -> List[str]:
669
+ result: List[str] = []
670
+ for t in tokens:
671
+ result.extend(expand_word(t, state))
672
+ return result
673
+
674
+
675
+ def expand_value(tok: Token, state: ShellState) -> str:
676
+ """Expand an assignment value. No globbing."""
677
+ return "".join(expand_word(tok, state, globbing=False, splitting=False, braces=False))
678
+
679
+
680
+ def expand_pattern(tok: Token, state: ShellState) -> str:
681
+ """Expand a case pattern. Quoted characters are literal, the rest may be wildcards."""
682
+ out: List[str] = []
683
+ for idx, (text, mode) in enumerate(tok.parts):
684
+ if mode == "single":
685
+ out.append(glob.escape(text))
686
+ elif mode == "double":
687
+ out.append(glob.escape(expand_vars(text, state)))
688
+ else:
689
+ if idx == 0:
690
+ text = expand_user(text)
691
+ out.append("".join(seg for seg, _ in expand_segments(text, state)))
692
+ return "".join(out)
693
+
694
+
695
+ def split_assignment(tok: Token) -> Optional[Tuple[str, Token]]:
696
+ """If the word looks like NAME=value, return (NAME, token for the value)."""
697
+ if tok.kind != WORD or not tok.parts or tok.parts[0][1] != "plain":
698
+ return None
699
+ m = ASSIGN_RE.fullmatch(tok.parts[0][0])
700
+ if not m:
701
+ return None
702
+ rest = m.group(2)
703
+ parts = ([(rest, "plain")] if rest else []) + tok.parts[1:]
704
+ return m.group(1), Token(WORD, parts)