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/lexer.py ADDED
@@ -0,0 +1,246 @@
1
+ """Lexer: turns a line of text into tokens. Quotes and operators are resolved here."""
2
+ from dataclasses import dataclass, field
3
+ from typing import List, Tuple
4
+
5
+ from .errors import ShellSyntaxError
6
+
7
+
8
+ WORD, PIPE, AND, OR, SEMI, BG, REDIR = "WORD", "PIPE", "AND", "OR", "SEMI", "BG", "REDIR"
9
+ DSEMI = "DSEMI" # ;; ends a case arm
10
+
11
+ # Longest operators first so "&>>" wins over "&>" and "&".
12
+ OPERATORS: List[Tuple[str, str]] = [
13
+ ("&>>", REDIR), ("2>>", REDIR), ("1>>", REDIR),
14
+ ("2>&1", REDIR), ("1>&2", REDIR), ("<<<", REDIR), ("<<-", REDIR),
15
+ ("<<", REDIR),
16
+ ("&&", AND), ("||", OR), ("&>", REDIR), ("2>", REDIR), ("1>", REDIR),
17
+ (">>", REDIR), (">&2", REDIR), (">&1", REDIR), ("<", REDIR),
18
+ ("|", PIPE), (";;", DSEMI), (";", SEMI), ("&", BG), (">", REDIR),
19
+ ]
20
+ # Operators that start with a digit only count at the start of a word.
21
+ FD_OPERATORS = ("2>>", "1>>", "2>&1", "1>&2", "2>", "1>")
22
+ COMMAND_START_AFTER = (PIPE, AND, OR, SEMI, BG, DSEMI)
23
+
24
+
25
+ @dataclass
26
+ class Token:
27
+ kind: str
28
+ # Each part is (text, mode). Mode is "plain", "single" or "double".
29
+ parts: List[Tuple[str, str]] = field(default_factory=list)
30
+
31
+ @property
32
+ def text(self) -> str:
33
+ return "".join(p[0] for p in self.parts)
34
+
35
+ @property
36
+ def quoted(self) -> bool:
37
+ return any(mode != "plain" for _, mode in self.parts)
38
+
39
+
40
+ def find_matching_paren(text: str, start: int) -> int:
41
+ """text[start] is '('. Return the index of the matching ')'."""
42
+ depth = 0
43
+ quote = None
44
+ i = start
45
+ while i < len(text):
46
+ c = text[i]
47
+ if quote == "'":
48
+ if c == "'":
49
+ quote = None
50
+ elif quote == "`":
51
+ if c == "\\":
52
+ i += 1
53
+ elif c == "`":
54
+ quote = None
55
+ elif quote == '"':
56
+ if c == "\\":
57
+ i += 1
58
+ elif c == '"':
59
+ quote = None
60
+ elif c == "\\":
61
+ i += 1
62
+ elif c in "'\"`":
63
+ quote = c
64
+ elif c == "(":
65
+ depth += 1
66
+ elif c == ")":
67
+ depth -= 1
68
+ if depth == 0:
69
+ return i
70
+ i += 1
71
+ raise ShellSyntaxError("unterminated command substitution")
72
+
73
+
74
+ def find_matching_brace(text: str, start: int) -> int:
75
+ """text[start] is '{' of a ${...} expansion. Return the index of the matching '}'.
76
+ Quotes and nested $(...) are skipped, nested braces count."""
77
+ depth = 0
78
+ quote = None
79
+ i = start
80
+ while i < len(text):
81
+ c = text[i]
82
+ if quote == "'":
83
+ if c == "'":
84
+ quote = None
85
+ elif quote == '"':
86
+ if c == "\\":
87
+ i += 1
88
+ elif c == '"':
89
+ quote = None
90
+ elif c == "\\":
91
+ i += 1
92
+ elif c in "'\"":
93
+ quote = c
94
+ elif c == "$" and text.startswith("$(", i):
95
+ i = find_matching_paren(text, i + 1)
96
+ elif c == "{":
97
+ depth += 1
98
+ elif c == "}":
99
+ depth -= 1
100
+ if depth == 0:
101
+ return i
102
+ i += 1
103
+ raise ShellSyntaxError("unterminated parameter expansion")
104
+
105
+
106
+ def read_backticks(text: str, start: int) -> Tuple[str, int]:
107
+ """text[start] is a backtick. Return (command text, index of the closing backtick).
108
+ Inside backticks a backslash before $, ` or \\ is removed. Other backslashes stay."""
109
+ out = ""
110
+ i = start + 1
111
+ while i < len(text):
112
+ c = text[i]
113
+ if c == "\\" and i + 1 < len(text) and text[i + 1] in "$`\\":
114
+ out += text[i + 1]
115
+ i += 2
116
+ elif c == "`":
117
+ return out, i
118
+ else:
119
+ out += c
120
+ i += 1
121
+ raise ShellSyntaxError("unterminated command substitution")
122
+
123
+
124
+ def lex(line: str) -> List[Token]:
125
+ tokens: List[Token] = []
126
+ parts: List[Tuple[str, str]] = []
127
+ buf = ""
128
+ mode = "plain"
129
+ has_word = False
130
+ i, n = 0, len(line)
131
+
132
+ def flush_buf():
133
+ nonlocal buf
134
+ if buf:
135
+ parts.append((buf, mode))
136
+ buf = ""
137
+
138
+ def close_quote():
139
+ # Unlike flush_buf, this keeps an empty part so that "" survives as an argument.
140
+ nonlocal buf
141
+ parts.append((buf, mode))
142
+ buf = ""
143
+
144
+ def end_word():
145
+ nonlocal parts, has_word
146
+ flush_buf()
147
+ if has_word:
148
+ tokens.append(Token(WORD, parts))
149
+ parts = []
150
+ has_word = False
151
+
152
+ while i < n:
153
+ c = line[i]
154
+ if mode == "single":
155
+ if c == "'":
156
+ close_quote()
157
+ mode = "plain"
158
+ else:
159
+ buf += c
160
+ i += 1
161
+ elif mode == "double":
162
+ if c == '"':
163
+ close_quote()
164
+ mode = "plain"
165
+ i += 1
166
+ elif c == "$" and line.startswith("$(", i):
167
+ end = find_matching_paren(line, i + 1)
168
+ buf += line[i:end + 1] # kept whole. Expansion runs it later.
169
+ i = end + 1
170
+ elif c == "$" and line.startswith("${", i):
171
+ end = find_matching_brace(line, i + 1)
172
+ buf += line[i:end + 1] # kept whole. Expansion runs it later.
173
+ i = end + 1
174
+ elif c == "`":
175
+ inner, end = read_backticks(line, i)
176
+ buf += "$(" + inner + ")" # same as $(...) from here on
177
+ i = end + 1
178
+ elif c == "\\" and i + 1 < n and line[i + 1] in '"\\$`':
179
+ if line[i + 1] == "$":
180
+ # An escaped dollar sign stays literal. Store it as its own part.
181
+ flush_buf()
182
+ parts.append(("$", "single"))
183
+ else:
184
+ buf += line[i + 1]
185
+ i += 2
186
+ else:
187
+ buf += c
188
+ i += 1
189
+ else:
190
+ if c == "'" or c == '"':
191
+ flush_buf()
192
+ mode = "single" if c == "'" else "double"
193
+ has_word = True
194
+ i += 1
195
+ elif c == "$" and line.startswith("$(", i):
196
+ end = find_matching_paren(line, i + 1)
197
+ buf += line[i:end + 1] # kept whole. Expansion runs it later.
198
+ has_word = True
199
+ i = end + 1
200
+ elif c == "$" and line.startswith("${", i):
201
+ end = find_matching_brace(line, i + 1)
202
+ buf += line[i:end + 1] # kept whole. Expansion runs it later.
203
+ has_word = True
204
+ i = end + 1
205
+ elif c == "`":
206
+ inner, end = read_backticks(line, i)
207
+ buf += "$(" + inner + ")"
208
+ has_word = True
209
+ i = end + 1
210
+ elif c == "\\":
211
+ flush_buf()
212
+ if i + 1 < n:
213
+ parts.append((line[i + 1], "single"))
214
+ i += 2
215
+ else:
216
+ parts.append(("\\", "single"))
217
+ i += 1
218
+ has_word = True
219
+ elif c.isspace():
220
+ end_word()
221
+ i += 1
222
+ elif c == "#" and not has_word and not buf:
223
+ break # a comment runs to the end of the line
224
+ else:
225
+ matched = None
226
+ for op, kind in OPERATORS:
227
+ if not line.startswith(op, i):
228
+ continue
229
+ if op in FD_OPERATORS and (has_word or buf):
230
+ continue
231
+ matched = (op, kind)
232
+ break
233
+ if matched:
234
+ end_word()
235
+ op, kind = matched
236
+ tokens.append(Token(kind, [(op, "plain")]))
237
+ i += len(op)
238
+ else:
239
+ buf += c
240
+ has_word = True
241
+ i += 1
242
+
243
+ if mode != "plain":
244
+ raise ShellSyntaxError("unterminated quote")
245
+ end_word()
246
+ return tokens