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/parser.py ADDED
@@ -0,0 +1,437 @@
1
+ """Parser: turns tokens into a tree of lists, pipelines and commands."""
2
+ import re
3
+ from dataclasses import dataclass, field
4
+ from typing import Iterator, List, Optional, Tuple, Union
5
+
6
+ from .errors import ShellSyntaxError
7
+ from .lexer import AND, BG, DSEMI, OR, PIPE, REDIR, SEMI, WORD, Token
8
+
9
+
10
+ NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
11
+
12
+
13
+ # Parser: tokens -> syntax tree
14
+ #
15
+ # list := pipeline ( ('&&' | '||' | ';' | '&') pipeline )* [';' | '&']
16
+ # pipeline := command ( '|' command )*
17
+ # command := ( WORD | REDIR WORD )+
18
+ # Redirections that copy one stream onto another and take no file name.
19
+ DUP_OPS = ("2>&1", "1>&2", ">&2", ">&1")
20
+
21
+
22
+ @dataclass
23
+ class Redirect:
24
+ op: str
25
+ target: Optional[Token] = None # None for the DUP_OPS. The delimiter for << and <<-
26
+ body: str = "" # text of a here-document, filled in after parsing
27
+
28
+
29
+ @dataclass
30
+ class Command:
31
+ argv: List[Token]
32
+ redirects: List[Redirect] = field(default_factory=list)
33
+
34
+
35
+ @dataclass
36
+ class Pipeline:
37
+ commands: List[Command]
38
+ background: bool = False
39
+
40
+
41
+ @dataclass
42
+ class ListItem:
43
+ op: str # how this item links to the one before it: ';', '&&' or '||'
44
+ pipeline: Union[Pipeline, "IfClause", "WhileClause", "ForClause", "CaseClause", "Group", "FuncDef"]
45
+
46
+
47
+ @dataclass
48
+ class IfClause:
49
+ """if COND; then BODY; [elif COND; then BODY;] [else BODY;] fi"""
50
+ clauses: List[Tuple[List[ListItem], List[ListItem]]] # (condition, body) pairs
51
+ else_body: Optional[List[ListItem]] = None
52
+
53
+
54
+ @dataclass
55
+ class WhileClause:
56
+ """while COND; do BODY; done. With until=True the loop runs while COND fails."""
57
+ cond: List[ListItem]
58
+ body: List[ListItem]
59
+ until: bool = False
60
+
61
+
62
+ @dataclass
63
+ class ForClause:
64
+ """for NAME in WORDS; do BODY; done. Without `in`, words is None and the loop uses "$@"."""
65
+ name: str
66
+ words: Optional[List[Token]]
67
+ body: List[ListItem]
68
+
69
+
70
+ @dataclass
71
+ class CaseClause:
72
+ """case WORD in PATTERN|PATTERN) BODY ;; ... esac"""
73
+ word: Token
74
+ arms: List[Tuple[List[Token], List[ListItem]]] # (patterns, body) pairs
75
+
76
+
77
+ @dataclass
78
+ class Group:
79
+ """{ BODY; } runs in the current shell."""
80
+ body: List[ListItem]
81
+
82
+
83
+ @dataclass
84
+ class FuncDef:
85
+ """name() { BODY; }"""
86
+ name: str
87
+ body: List[ListItem]
88
+
89
+
90
+ def iter_commands(items: List[ListItem]) -> Iterator[Command]:
91
+ """Every simple command in the tree, in order, including those inside if blocks."""
92
+ for item in items:
93
+ node = item.pipeline
94
+ if isinstance(node, IfClause):
95
+ for cond, body in node.clauses:
96
+ yield from iter_commands(cond)
97
+ yield from iter_commands(body)
98
+ if node.else_body:
99
+ yield from iter_commands(node.else_body)
100
+ elif isinstance(node, WhileClause):
101
+ yield from iter_commands(node.cond)
102
+ yield from iter_commands(node.body)
103
+ elif isinstance(node, (ForClause, Group, FuncDef)):
104
+ yield from iter_commands(node.body)
105
+ elif isinstance(node, CaseClause):
106
+ for _, body in node.arms:
107
+ yield from iter_commands(body)
108
+ else:
109
+ yield from node.commands
110
+
111
+
112
+ def is_word(tok: Token, words) -> bool:
113
+ """True for an unquoted word that is one of words."""
114
+ return (tok.kind == WORD and len(tok.parts) == 1 and tok.parts[0][1] == "plain"
115
+ and tok.parts[0][0] in words)
116
+
117
+
118
+ FUNC_HEADER_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\(\)")
119
+
120
+
121
+ def ends_with_paren(tok: Token) -> bool:
122
+ return bool(tok.parts) and tok.parts[-1][1] == "plain" and tok.parts[-1][0].endswith(")")
123
+
124
+
125
+ def compound_open(tokens: List[Token]) -> bool:
126
+ """True when a block (if, while, until, for, case, { }) or a function header is not
127
+ finished yet, so more lines are needed."""
128
+ stack: List[str] = [] # "block", "case_head", "case_pat" or "case_body"
129
+ start = True # at the start of a command, where reserved words count
130
+ pat_start = False # at the start of a case pattern
131
+ header = False # the last token was a function header
132
+ prev_start_word = None
133
+ brace_ok = False # a { here opens a function body
134
+ function_kw = 0 # words left after the `function` keyword that may precede the body
135
+ for t in tokens:
136
+ top = stack[-1] if stack else None
137
+ was_start = start
138
+ header = False
139
+ body_may_open = brace_ok
140
+ brace_ok = False
141
+ if t.kind != WORD:
142
+ if t.kind == DSEMI and top == "case_body":
143
+ stack[-1] = "case_pat"
144
+ pat_start = True
145
+ start = False
146
+ elif t.kind == PIPE and top == "case_pat":
147
+ start = False
148
+ else:
149
+ start = t.kind in (PIPE, AND, OR, SEMI, BG)
150
+ prev_start_word = None
151
+ continue
152
+ if top == "case_head":
153
+ if is_word(t, ("in",)):
154
+ stack[-1] = "case_pat"
155
+ pat_start = True
156
+ start = False
157
+ elif top == "case_pat":
158
+ if pat_start and is_word(t, ("esac",)):
159
+ stack.pop()
160
+ elif ends_with_paren(t):
161
+ stack[-1] = "case_body"
162
+ start = True
163
+ pat_start = False
164
+ else:
165
+ pat_start = False
166
+ elif (start or (body_may_open and is_word(t, ("{",)))) and is_word(t, OPENERS):
167
+ stack.append("case_head" if t.text == "case" else "block")
168
+ start = t.text != "case"
169
+ elif start and is_word(t, CLOSERS):
170
+ if stack:
171
+ stack.pop()
172
+ start = False
173
+ else:
174
+ if was_start and t.parts[0][1] == "plain" and FUNC_HEADER_RE.fullmatch(t.text):
175
+ header = brace_ok = True
176
+ elif prev_start_word is not None and is_word(t, ("()",)):
177
+ header = brace_ok = True
178
+ elif was_start and is_word(t, ("function",)):
179
+ function_kw = 2
180
+ if function_kw and not header:
181
+ function_kw -= 1
182
+ brace_ok = True
183
+ start = start and is_word(t, ("then", "else", "elif", "do"))
184
+ prev_start_word = t if (was_start and not t.quoted and NAME_RE.fullmatch(t.text)) else None
185
+ return bool(stack) or header
186
+
187
+
188
+ OPENERS = ("if", "while", "until", "for", "case", "{")
189
+ CLOSERS = ("fi", "done", "esac", "}")
190
+
191
+
192
+ class Parser:
193
+ def __init__(self, tokens: List[Token]):
194
+ self.tokens = tokens
195
+ self.pos = 0
196
+
197
+ def peek(self) -> Optional[Token]:
198
+ return self.tokens[self.pos] if self.pos < len(self.tokens) else None
199
+
200
+ def unexpected(self) -> ShellSyntaxError:
201
+ t = self.peek()
202
+ if t is None:
203
+ return ShellSyntaxError("unexpected end of line")
204
+ return ShellSyntaxError(f"unexpected token `{t.text}'")
205
+
206
+ def at_word(self, words) -> bool:
207
+ t = self.peek()
208
+ return t is not None and is_word(t, words)
209
+
210
+ def expect_word(self, word: str) -> None:
211
+ if not self.at_word((word,)):
212
+ raise self.unexpected()
213
+ self.pos += 1
214
+
215
+ def parse_list(self, stop=()) -> List[ListItem]:
216
+ """Parse until the end of input or until a reserved word in `stop` starts a command."""
217
+ items: List[ListItem] = []
218
+ op = ";"
219
+ while self.peek() is not None:
220
+ if self.at_word(stop) or self.peek().kind == DSEMI:
221
+ break
222
+ if self.at_funcdef():
223
+ node = self.parse_funcdef()
224
+ elif self.at_word(("case",)):
225
+ node = self.parse_case()
226
+ elif self.at_word(("{",)):
227
+ node = self.parse_group()
228
+ elif self.at_word(("if",)):
229
+ node = self.parse_if()
230
+ elif self.at_word(("while", "until")):
231
+ node = self.parse_while()
232
+ elif self.at_word(("for",)):
233
+ node = self.parse_for()
234
+ else:
235
+ node = self.parse_pipeline()
236
+ t = self.peek()
237
+ if not isinstance(node, Pipeline) and t is not None and t.kind not in (AND, OR, SEMI, BG, DSEMI):
238
+ raise self.unexpected() # no pipes or redirects after fi
239
+ if t is not None and t.kind == BG:
240
+ if not isinstance(node, Pipeline):
241
+ raise ShellSyntaxError("background compound commands are not supported")
242
+ self.pos += 1
243
+ node.background = True
244
+ items.append(ListItem(op, node))
245
+ op = ";"
246
+ continue
247
+ items.append(ListItem(op, node))
248
+ if t is None or t.kind == DSEMI:
249
+ break
250
+ self.pos += 1 # consume && || or ;
251
+ op = t.text
252
+ if self.peek() is None:
253
+ if op in ("&&", "||"):
254
+ raise ShellSyntaxError("unexpected end of line")
255
+ break # trailing ';'
256
+ return items
257
+
258
+ def parse_block(self, stop) -> List[ListItem]:
259
+ items = self.parse_list(stop)
260
+ if not items:
261
+ raise self.unexpected()
262
+ return items
263
+
264
+ def parse_if(self) -> IfClause:
265
+ self.pos += 1 # if
266
+ clauses = []
267
+ while True:
268
+ cond = self.parse_block(("then",))
269
+ self.expect_word("then")
270
+ body = self.parse_block(("elif", "else", "fi"))
271
+ clauses.append((cond, body))
272
+ if self.at_word(("elif",)):
273
+ self.pos += 1
274
+ continue
275
+ break
276
+ else_body = None
277
+ if self.at_word(("else",)):
278
+ self.pos += 1
279
+ else_body = self.parse_block(("fi",))
280
+ self.expect_word("fi")
281
+ return IfClause(clauses, else_body)
282
+
283
+ def parse_while(self) -> WhileClause:
284
+ until = self.tokens[self.pos].text == "until"
285
+ self.pos += 1
286
+ cond = self.parse_block(("do",))
287
+ self.expect_word("do")
288
+ body = self.parse_block(("done",))
289
+ self.expect_word("done")
290
+ return WhileClause(cond, body, until)
291
+
292
+ def parse_for(self) -> ForClause:
293
+ self.pos += 1 # for
294
+ t = self.peek()
295
+ if t is None or t.kind != WORD or t.quoted or not NAME_RE.fullmatch(t.text):
296
+ raise self.unexpected()
297
+ name = t.text
298
+ self.pos += 1
299
+ words: Optional[List[Token]] = None
300
+ if self.at_word(("in",)):
301
+ self.pos += 1
302
+ words = []
303
+ while self.peek() is not None and self.peek().kind == WORD:
304
+ words.append(self.peek())
305
+ self.pos += 1
306
+ if self.peek() is not None and self.peek().kind == SEMI:
307
+ self.pos += 1
308
+ self.expect_word("do")
309
+ body = self.parse_block(("done",))
310
+ self.expect_word("done")
311
+ return ForClause(name, words, body)
312
+
313
+ def skip_semis(self) -> None:
314
+ while self.peek() is not None and self.peek().kind == SEMI:
315
+ self.pos += 1
316
+
317
+ def at_funcdef(self) -> bool:
318
+ t = self.peek()
319
+ if t is None or t.kind != WORD or t.quoted:
320
+ return False
321
+ if FUNC_HEADER_RE.fullmatch(t.text):
322
+ return True
323
+ nxt = self.tokens[self.pos + 1] if self.pos + 1 < len(self.tokens) else None
324
+ if t.text == "function":
325
+ return nxt is not None and nxt.kind == WORD and not nxt.quoted
326
+ return bool(NAME_RE.fullmatch(t.text) and nxt is not None and is_word(nxt, ("()",)))
327
+
328
+ def parse_funcdef(self) -> FuncDef:
329
+ t = self.peek()
330
+ self.pos += 1
331
+ if t.text == "function":
332
+ name = self.peek().text
333
+ self.pos += 1
334
+ if self.peek() is not None and is_word(self.peek(), ("()",)):
335
+ self.pos += 1
336
+ elif FUNC_HEADER_RE.fullmatch(t.text):
337
+ name = t.text[:-2]
338
+ else:
339
+ name = t.text
340
+ self.pos += 1 # the "()" word
341
+ name = name.rstrip("()")
342
+ if not NAME_RE.fullmatch(name):
343
+ raise ShellSyntaxError(f"`{name}': not a valid function name")
344
+ self.skip_semis()
345
+ if not self.at_word(("{",)):
346
+ raise self.unexpected()
347
+ return FuncDef(name, self.parse_group().body)
348
+
349
+ def parse_group(self) -> Group:
350
+ self.expect_word("{")
351
+ body = self.parse_block(("}",))
352
+ self.expect_word("}")
353
+ return Group(body)
354
+
355
+ def parse_case(self) -> CaseClause:
356
+ self.pos += 1 # case
357
+ word = self.peek()
358
+ if word is None or word.kind != WORD:
359
+ raise self.unexpected()
360
+ self.pos += 1
361
+ self.skip_semis()
362
+ self.expect_word("in")
363
+ self.skip_semis()
364
+ arms: List[Tuple[List[Token], List[ListItem]]] = []
365
+ while not self.at_word(("esac",)):
366
+ patterns: List[Token] = []
367
+ first = True
368
+ while True:
369
+ t = self.peek()
370
+ if t is None or t.kind != WORD:
371
+ raise self.unexpected()
372
+ self.pos += 1
373
+ parts = list(t.parts)
374
+ if first and parts[0][1] == "plain" and parts[0][0].startswith("("):
375
+ parts[0] = (parts[0][0][1:], "plain")
376
+ closes = bool(parts) and parts[-1][1] == "plain" and parts[-1][0].endswith(")")
377
+ if closes:
378
+ parts[-1] = (parts[-1][0][:-1], "plain")
379
+ if any(text for text, _ in parts) or any(mode != "plain" for _, mode in parts):
380
+ patterns.append(Token(WORD, [p for p in parts if p[0] or p[1] != "plain"]))
381
+ if closes:
382
+ break
383
+ if self.peek() is not None and self.peek().kind == PIPE:
384
+ self.pos += 1
385
+ first = False
386
+ continue
387
+ if self.peek() is not None and is_word(self.peek(), (")",)):
388
+ continue # a lone ")" closes the patterns on the next round
389
+ raise self.unexpected()
390
+ if not patterns:
391
+ raise self.unexpected()
392
+ self.skip_semis()
393
+ body = self.parse_list(("esac",))
394
+ if self.peek() is not None and self.peek().kind == DSEMI:
395
+ self.pos += 1
396
+ self.skip_semis()
397
+ arms.append((patterns, body))
398
+ self.expect_word("esac")
399
+ return CaseClause(word, arms)
400
+
401
+ def parse_pipeline(self) -> Pipeline:
402
+ commands = [self.parse_command()]
403
+ while self.peek() is not None and self.peek().kind == PIPE:
404
+ self.pos += 1
405
+ commands.append(self.parse_command())
406
+ return Pipeline(commands)
407
+
408
+ def parse_command(self) -> Command:
409
+ argv: List[Token] = []
410
+ redirects: List[Redirect] = []
411
+ while True:
412
+ t = self.peek()
413
+ if t is None or t.kind not in (WORD, REDIR):
414
+ break
415
+ self.pos += 1
416
+ if t.kind == WORD:
417
+ argv.append(t)
418
+ continue
419
+ if t.text in DUP_OPS:
420
+ redirects.append(Redirect(t.text))
421
+ continue
422
+ target = self.peek()
423
+ if target is None or target.kind != WORD:
424
+ raise self.unexpected()
425
+ self.pos += 1
426
+ redirects.append(Redirect(t.text, target))
427
+ if not argv and not redirects:
428
+ raise self.unexpected()
429
+ return Command(argv, redirects)
430
+
431
+
432
+ def parse(tokens: List[Token]) -> List[ListItem]:
433
+ parser = Parser(tokens)
434
+ items = parser.parse_list()
435
+ if parser.peek() is not None:
436
+ raise parser.unexpected() # for example a stray ;;
437
+ return items
myshell/paths.py ADDED
@@ -0,0 +1,18 @@
1
+ """The home folder. HOME wins when it is set, because Windows ignores it otherwise."""
2
+ import os
3
+
4
+
5
+ def home_dir() -> str:
6
+ return os.environ.get("HOME") or os.path.expanduser("~")
7
+
8
+
9
+ def expand_user(text: str) -> str:
10
+ """Like os.path.expanduser, but a plain ~ or ~/ uses HOME when HOME is set."""
11
+ home = os.environ.get("HOME")
12
+ if home and (text == "~" or text.startswith("~/") or (os.sep != "/" and text.startswith("~" + os.sep))):
13
+ return home + text[1:]
14
+ return os.path.expanduser(text)
15
+
16
+
17
+ def home_file(name: str) -> str:
18
+ return os.path.join(home_dir(), name)
myshell/progress.py ADDED
@@ -0,0 +1,98 @@
1
+ """Pip's progress record: which lessons you finished and how your quizzes went.
2
+ It lives in a small JSON file (state.progress_file, by default ~/.myshell_progress.json).
3
+ A missing or damaged file just means a fresh start."""
4
+ import json
5
+ import os
6
+ import time
7
+ from typing import Dict, List, Tuple
8
+
9
+ KEEP_RUNS = 20
10
+
11
+
12
+ def empty() -> dict:
13
+ return {"lessons": {}, "quizzes": {"runs": [], "best": {}}}
14
+
15
+
16
+ def load(path: str) -> dict:
17
+ try:
18
+ with open(path, encoding="utf-8") as f:
19
+ data = json.load(f)
20
+ except (OSError, ValueError):
21
+ return empty()
22
+ base = empty()
23
+ if isinstance(data, dict):
24
+ if isinstance(data.get("lessons"), dict):
25
+ base["lessons"] = data["lessons"]
26
+ quizzes = data.get("quizzes")
27
+ if isinstance(quizzes, dict):
28
+ if isinstance(quizzes.get("runs"), list):
29
+ base["quizzes"]["runs"] = quizzes["runs"]
30
+ if isinstance(quizzes.get("best"), dict):
31
+ base["quizzes"]["best"] = quizzes["best"]
32
+ return base
33
+
34
+
35
+ def save(path: str, data: dict) -> bool:
36
+ """Write the file in one step. Returns False when the disk refuses."""
37
+ tmp = path + ".tmp"
38
+ try:
39
+ with open(tmp, "w", encoding="utf-8") as f:
40
+ json.dump(data, f, indent=2, sort_keys=True)
41
+ os.replace(tmp, path)
42
+ return True
43
+ except OSError:
44
+ try:
45
+ os.remove(tmp)
46
+ except OSError:
47
+ pass
48
+ return False
49
+
50
+
51
+ def stamp() -> str:
52
+ return time.strftime("%Y-%m-%d %H:%M")
53
+
54
+
55
+ def mark_lesson(path: str, key: str) -> None:
56
+ data = load(path)
57
+ entry = data["lessons"].get(key, {})
58
+ entry = entry if isinstance(entry, dict) else {}
59
+ entry["times"] = int(entry.get("times", 0)) + 1
60
+ entry["last"] = stamp()
61
+ data["lessons"][key] = entry
62
+ save(path, data)
63
+
64
+
65
+ def record_quiz(path: str, topic: str, score: int, total: int) -> bool:
66
+ """Save a finished quiz. Returns True when this is a new best for the topic."""
67
+ data = load(path)
68
+ runs = data["quizzes"]["runs"]
69
+ runs.append({"topic": topic, "score": score, "total": total, "when": stamp()})
70
+ del runs[:-KEEP_RUNS]
71
+ best = data["quizzes"]["best"]
72
+ old = best.get(topic)
73
+ ratio = score / total if total else 0
74
+ is_best = not (isinstance(old, list) and len(old) == 2 and old[1]
75
+ and old[0] / old[1] >= ratio)
76
+ if is_best:
77
+ best[topic] = [score, total]
78
+ save(path, data)
79
+ return is_best
80
+
81
+
82
+ def done_lessons(path: str) -> List[str]:
83
+ return sorted(load(path)["lessons"])
84
+
85
+
86
+ def best_scores(path: str) -> Dict[str, Tuple[int, int]]:
87
+ out = {}
88
+ for topic, value in load(path)["quizzes"]["best"].items():
89
+ if isinstance(value, list) and len(value) == 2:
90
+ out[topic] = (int(value[0]), int(value[1]))
91
+ return out
92
+
93
+
94
+ def reset(path: str) -> None:
95
+ try:
96
+ os.remove(path)
97
+ except OSError:
98
+ pass