gcrsim 0.1.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.
gcrsim/__init__.py ADDED
@@ -0,0 +1,40 @@
1
+ """gcrsim - Graph Controlled string Rewriting SIMulator.
2
+
3
+ Importing this package has no side effects: it does not read files, print,
4
+ or start the command line interface."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from ._meta import __version__
9
+ from .cli import main
10
+ from .convert import convert_model
11
+ from .engine import Context, DerivationStep, Mark, Simulator, format_derivation
12
+ from .errors import CallbackError, ConfigError, GcrsimError, LimitReached, ModelError, TraceError
13
+ from .model import Model, parse_model, parse_model_file
14
+ from .output import Output, digest_contents, format_conf
15
+ from .rules import Rule
16
+ from .settings import Settings, apply_settings, load_config, resolve_config
17
+
18
+ __all__ = [
19
+ "__version__",
20
+ "GcrsimError",
21
+ "ModelError",
22
+ "ConfigError",
23
+ "LimitReached",
24
+ "TraceError",
25
+ "CallbackError",
26
+ "Model",
27
+ "Rule",
28
+ "Settings",
29
+ "Simulator",
30
+ "Output",
31
+ "DerivationStep",
32
+ "parse_model",
33
+ "parse_model_file",
34
+ "load_config",
35
+ "resolve_config",
36
+ "format_conf",
37
+ "format_derivation",
38
+ "digest_contents",
39
+ "main",
40
+ ]
gcrsim/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """python -m gcrsim"""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ sys.exit(main())
gcrsim/_meta.py ADDED
@@ -0,0 +1,6 @@
1
+ """Version and shared constants."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ # Version line of the Perl simulator whose behaviour is reproduced.
6
+ CHECK_FAILED_STATUS = 4 # --fail-on-mark: a mark with a failing label was recorded
gcrsim/_reference.py ADDED
@@ -0,0 +1,155 @@
1
+ """Independent reference interpreter for the plain fragment, written from SPEC.md.
2
+
3
+ It was written by a different author (Codex, from the text of SPEC.md alone, without access to the
4
+ engine) and is used by the tests and by ``--cross-check`` to check the engine. It uses no regular
5
+ expressions and works on tuples of symbols; clarity matters more than speed.
6
+ """
7
+ # reference.py
8
+ from typing import NamedTuple
9
+
10
+
11
+ START = object()
12
+ END = object()
13
+ ANY = object()
14
+
15
+
16
+ class Rule(NamedTuple):
17
+ kind: str
18
+ source: int
19
+ target: int
20
+ u: tuple = ()
21
+ x: tuple = () # items that are matched and replaced
22
+ y: tuple = () # the string that replaces them
23
+ v: tuple = ()
24
+ permit: tuple = ()
25
+ forbid: tuple = ()
26
+ permit_any: tuple = ()
27
+
28
+
29
+ def _validate_rule(rule):
30
+ if rule.kind not in ("sub", "send"):
31
+ raise ValueError("rule kind must be 'sub' or 'send'")
32
+ for word in rule.permit + rule.forbid + rule.permit_any:
33
+ if len(word) == 0:
34
+ raise ValueError("permit and forbid words must be non-empty")
35
+
36
+
37
+ def _occurs(word, s):
38
+ for i in range(len(s) - len(word) + 1):
39
+ if s[i:i + len(word)] == word:
40
+ return True
41
+ return False
42
+
43
+
44
+ def _match(items, s, pos):
45
+ """Return the final cursor, or None on failure."""
46
+ for item in items:
47
+ if item is START:
48
+ if pos != 0:
49
+ return None
50
+ elif item is END:
51
+ if pos != len(s):
52
+ return None
53
+ else:
54
+ if pos == len(s):
55
+ return None
56
+ if item is ANY:
57
+ pass
58
+ elif isinstance(item, frozenset):
59
+ if s[pos] not in item:
60
+ return None
61
+ elif s[pos] != item:
62
+ return None
63
+ pos += 1
64
+ return pos
65
+
66
+
67
+ def edits(rule, s):
68
+ _validate_rule(rule)
69
+
70
+ for word in rule.permit:
71
+ if not _occurs(word, s):
72
+ return []
73
+ for word in rule.forbid:
74
+ if _occurs(word, s):
75
+ return []
76
+ if rule.permit_any and not any(_occurs(word, s) for word in rule.permit_any):
77
+ return []
78
+
79
+ if rule.kind == "send":
80
+ return [(0, 0, ())]
81
+
82
+ result = []
83
+ for i in range(len(s) + 1):
84
+ p = _match(rule.u, s, i)
85
+ if p is None:
86
+ continue
87
+ q = _match(rule.x, s, p)
88
+ if q is None:
89
+ continue
90
+ if _match(rule.v, s, q) is None:
91
+ continue
92
+ result.append((p, q, rule.y))
93
+ return result
94
+
95
+
96
+ def candidates(rule, s):
97
+ return [
98
+ s[:p] + replacement + s[q:]
99
+ for p, q, replacement in edits(rule, s)
100
+ ]
101
+
102
+
103
+ def step(contents, history, rules, use_history, max_len):
104
+ rules = tuple(rules)
105
+ for rule in rules:
106
+ _validate_rule(rule)
107
+
108
+ if use_history:
109
+ if history is None or any(h is None for h in history):
110
+ raise ValueError("history must contain a set for each component")
111
+ new_history = [set(h) for h in history]
112
+ else:
113
+ new_history = None
114
+
115
+ raw_candidates = [[] for _ in contents]
116
+ for c, content in enumerate(contents):
117
+ for s in content:
118
+ for rule in rules:
119
+ if rule.source == c:
120
+ raw_candidates[rule.target].extend(candidates(rule, s))
121
+
122
+ new_contents = [[] for _ in contents]
123
+ for target, generated in enumerate(raw_candidates):
124
+ seen = new_history[target] if use_history else set()
125
+ for word in generated:
126
+ if word in seen:
127
+ continue
128
+ seen.add(word)
129
+ if max_len is not None and len(word) > max_len:
130
+ continue
131
+ new_contents[target].append(word)
132
+
133
+ raw_candidate_count = sum(len(words) for words in raw_candidates)
134
+ return new_contents, new_history, raw_candidate_count
135
+
136
+
137
+ def run(axioms, rules, steps, use_history=True, max_len=None):
138
+ if steps < 0:
139
+ raise ValueError("steps must be non-negative")
140
+
141
+ rules = tuple(rules)
142
+ for rule in rules:
143
+ _validate_rule(rule)
144
+
145
+ contents = [list(content) for content in axioms]
146
+ history = [set(content) for content in contents] if use_history else None
147
+ result = [{"contents": contents, "raw": 0}]
148
+
149
+ for _ in range(steps):
150
+ contents, history, raw = step(
151
+ contents, history, rules, use_history, max_len
152
+ )
153
+ result.append({"contents": contents, "raw": raw})
154
+
155
+ return result
gcrsim/cli.py ADDED
@@ -0,0 +1,478 @@
1
+ """Command line interface: argument parsing, header, listings, `main`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ import time
8
+ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
9
+ from ._meta import CHECK_FAILED_STATUS, __version__
10
+ from .engine import DerivationStep, Mark, Simulator, format_derivation
11
+ from . import listing, stepper
12
+ from .errors import GcrsimError, LimitReached, TraceError
13
+ from .pattern import make_matcher
14
+ from .model import parse_model_file
15
+ from .output import Output, format_conf
16
+ from .retention import SqliteRetention
17
+ from .verify import Verifier
18
+ from .settings import Settings, apply_settings, read_config_data, resolve_config
19
+
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Command line interface
23
+ # ---------------------------------------------------------------------------
24
+
25
+
26
+ def _build_parser() -> "argparse.ArgumentParser":
27
+ import argparse
28
+
29
+ p = argparse.ArgumentParser(
30
+ prog="gcrsim",
31
+ description="Graph Controlled string Rewriting SIMulator (successor of the Perl gcrsim.pl).",
32
+ epilog="Other programs: 'gcrsim-convert OLD_MODEL [-o NEW_MODEL]' translates a Perl-era model and its .cfg; "
33
+ "'gcrsim-retention FILE ...' shows, searches and traces a file written with --retain-file. "
34
+ "Use --help with them for their options.",
35
+ )
36
+ p.add_argument("input_file", nargs="?", help="model file (asked for interactively if omitted)")
37
+ p.add_argument("steps", nargs="?", help="number of steps to run (or the setting 'steps' of the configuration)")
38
+ p.add_argument("-i", "--interactive", action="store_true", help="step by step, waiting for a command after each step (formats text and perl only)")
39
+ p.add_argument("--format", choices=("text", "perl", "csv", "jsonl"), default="text",
40
+ help="text: a short header and the strings of each step (default); perl: the layout of the Perl simulator; "
41
+ "csv: only the strings, one row each; jsonl: one JSON object per line (header, one per step, messages, end)")
42
+ p.add_argument("--csv-sep", metavar="CHAR", default="tab",
43
+ help="separator of the csv format: one character (for example , or ;) or tab (the default)")
44
+ p.add_argument("--version", action="version", version="gcrsim %s" % __version__)
45
+ p.add_argument("--config", metavar="FILE", action="append", default=[],
46
+ help="configuration (.toml with [model] and [run]) applied over the model's own settings; repeatable, later files win")
47
+ p.add_argument("--python-filter", metavar="FILE.py",
48
+ help="run FILE.py (it executes code!): a Python function keep(s, component[, ctx]) that rejects strings, "
49
+ "and any other setting, applied on top of the configuration")
50
+ p.add_argument("--quiet", action="store_true", help="no header, step banners or listings (callback output stays)")
51
+ p.add_argument("--progress", action="store_true", help="write one summary line per step to stderr")
52
+ p.add_argument("--no-mark-summary", action="store_true", help="do not list the marks at the end of the run")
53
+ p.add_argument("--print-all", action="store_true", help="ignore print_hide/print_max_len (list every accepted string)")
54
+ p.add_argument("--run-empty", action="store_true", help="keep running steps after all components are empty")
55
+ p.add_argument("--streaming", action="store_true", help="filter candidates as they are generated (pure callbacks only)")
56
+ p.add_argument("--cross-check", action="store_true",
57
+ help="run an independent reference interpreter next to the engine and compare every step (plain fragment only)")
58
+ p.add_argument("--no-mark-rejected", action="store_true", help="do not record strings rejected by pure conditions in the history")
59
+ t = p.add_argument_group("trace-back")
60
+ t.add_argument("--trace", metavar="STRING", help="print the derivation of STRING when it first appears")
61
+ t.add_argument("--component", type=int, default=1, metavar="N", help="component of --trace STRING (default 1)")
62
+ t.add_argument("--trace-marks", action="store_true", help="retain the strings of every step and print a derivation for every mark")
63
+ t.add_argument("--trace-mark-label", action="append", default=[], metavar="LABEL",
64
+ help="derivations only for marks with this label (repeatable; implies --trace-marks)")
65
+ t.add_argument("--stop-on-mark-label", action="append", default=[], metavar="LABEL",
66
+ help="stop after the step in which a mark with this label was recorded (repeatable)")
67
+ t.add_argument("--fail-on-mark", action="append", default=[], metavar="LABEL",
68
+ help="exit with status 4 if a mark with this label was recorded; '*' means any label (repeatable)")
69
+ t.add_argument("--stop-on-found", action="store_true", help="stop after the step in which --trace STRING appeared")
70
+ t.add_argument("--stop-on-mark", action="store_true", help="stop after the step in which a callback marked a string")
71
+ t.add_argument("--max-retained", type=int, metavar="N", help="cap on strings retained for trace-back")
72
+ t.add_argument("--retain-file", metavar="FILE", help="keep the retained strings in this SQLite file instead of in memory (for long traces)")
73
+ t.add_argument("--trace-best-effort", action="store_true", help="when --max-retained is hit, continue without tracing")
74
+ lim = p.add_argument_group("limits (stop the run with status 3; the last step is incomplete)")
75
+ lim.add_argument("--max-step-candidates", type=int, metavar="N", help="candidates generated in one step (a per-step limit)")
76
+ lim.add_argument("--max-history", type=int, metavar="N", help="strings inserted into the history (whole run)")
77
+ lim.add_argument("--max-step-accepted", type=int, metavar="N", help="strings accepted in one step, over all components (a per-step limit)")
78
+ lim.add_argument("--max-marks", type=int, metavar="N", help="marks recorded (whole run)")
79
+ return p
80
+
81
+
82
+ class _LineSink:
83
+ """A stand-in for ``sys.stdout`` that passes whole lines to ``emit`` (``print`` writes a line in pieces)."""
84
+
85
+ def __init__(self, emit: Callable[[str], Any]):
86
+ self._emit = emit
87
+ self._pending = ""
88
+
89
+ def write(self, text: str) -> int:
90
+ self._pending += text
91
+ head, newline, self._pending = self._pending.rpartition("\n")
92
+ if newline:
93
+ self._emit(head + "\n")
94
+ return len(text)
95
+
96
+ def flush(self) -> None:
97
+ if self._pending:
98
+ self._emit(self._pending + "\n")
99
+ self._pending = ""
100
+
101
+
102
+ def _header(out: Output, model_path: str, st: Settings, has_filter: bool) -> None:
103
+ w = out.write
104
+ w("\n\n========================================\n")
105
+ w("gcrsim simulator v.%s\n" % __version__)
106
+ w("Program configuration:\n")
107
+ w("Input file: %s\n" % model_path)
108
+ w("Configuration: %s\n" % st.config_name)
109
+ if st.description:
110
+ w("Description: %s\n" % st.description)
111
+ w('Print_hide = "%s"; Print_max_len=%s;\n' % (st.print_hide, "unlimited" if st.print_max_len is None else st.print_max_len))
112
+ w('Reject_strings = "%s"; Reject_max_len=%s\n' % (st.reject_strings, "unlimited" if st.reject_max_len is None else st.reject_max_len))
113
+ w("Filter function used: %s, History: %s\n" % ("yes" if has_filter else "no", "yes" if st.history else "no"))
114
+ w("========================================\n")
115
+ w("The initial configuration (at STEP 0):\n\n")
116
+
117
+
118
+ def _non_default(st: Settings) -> List[str]:
119
+ """The settings of a run that differ from the defaults, for the header of the text format."""
120
+ d = Settings()
121
+ items: List[str] = []
122
+ if st.print_hide != d.print_hide:
123
+ items.append('print_hide "%s"' % st.print_hide)
124
+ if st.print_max_len != d.print_max_len:
125
+ items.append("print_max_len %s" % st.print_max_len)
126
+ if st.reject_strings != d.reject_strings:
127
+ items.append('reject_strings "%s"' % st.reject_strings)
128
+ if st.reject_max_len != d.reject_max_len:
129
+ items.append("reject_max_len %s" % st.reject_max_len)
130
+ if st.history != d.history:
131
+ items.append("history off")
132
+ if st.show_detailed_application:
133
+ items.append("detailed application")
134
+ if st.print_sep:
135
+ items.append('print_sep "%s"' % st.print_sep)
136
+ if st.hash_history:
137
+ items.append("hash_history")
138
+ for what, table in (("filters", st.filters), ("marks", st.marks)):
139
+ if table:
140
+ items.append("%s for %d component%s" % (what, len(table), "" if len(table) == 1 else "s"))
141
+ if st.filter_next is not None:
142
+ items.append("filter function")
143
+ return items
144
+
145
+
146
+ def _text_header(out: Output, model_path: str, st: Settings, model: Any) -> None:
147
+ """The header of the text format: what was run, and only what differs from the defaults."""
148
+ w = out.write
149
+ w("gcrsim %s %s\n" % (__version__, model_path))
150
+ if st.description:
151
+ w(st.description + "\n")
152
+ rules = sum(len(r) for r in model.rules)
153
+ line = "%d component%s, %d rule%s" % (model.ncomp, "" if model.ncomp == 1 else "s", rules, "" if rules == 1 else "s")
154
+ if st.config_name != "model":
155
+ line += "; settings: " + st.config_name
156
+ w(line + "\n")
157
+ items = _non_default(st)
158
+ if items:
159
+ w(", ".join(items) + "\n")
160
+ w("\n")
161
+
162
+
163
+ def _print_text_conf(out: Output, contents: Sequence[Sequence[str]], skip: Optional[Callable[[str], Any]], plen: Optional[int]) -> None:
164
+ """The strings of each component in the text format: a heading, one string per line, a blank line. An empty component
165
+ is just the heading and the blank line; the empty word is written (empty word)."""
166
+ for c, comp in enumerate(listing.visible(contents, skip, plen)):
167
+ out.write("component %d\n" % (c + 1))
168
+ for string in comp:
169
+ out.write((string or "(empty word)") + "\n")
170
+ out.write("\n")
171
+
172
+
173
+ def _print_conf(out: Output, contents: Sequence[Sequence[str]], skip: Optional[Callable[[str], Any]], plen: Optional[int]) -> None:
174
+ for chunk in format_conf(contents, skip, plen):
175
+ out.write(chunk)
176
+
177
+
178
+ def _print_marks_block(out: Output, sim: Simulator, new_marks: Sequence[Mark], retain: bool) -> None:
179
+ if not new_marks or not retain:
180
+ return # without retention the inline mark line (and the final summary) is all there is
181
+ derivs: List[Optional[List[DerivationStep]]] = [None] * len(new_marks)
182
+ note = ""
183
+ try:
184
+ chains = sim._trace_many([(m.component, m.encoded, m.step) for m in new_marks])
185
+ derivs = list(chains)
186
+ except TraceError as exc:
187
+ note = " (derivation unavailable: %s)\n" % exc
188
+ for m, d in zip(new_marks, derivs):
189
+ out.write("\nMark [%s] at step %d, component %d: %s\n" % (m.label, m.step, m.component + 1, m.encoded))
190
+ if d is not None:
191
+ out.write(format_derivation(d))
192
+ else:
193
+ out.write(note)
194
+
195
+
196
+ def _print_marks_summary(out: Output, marks: Sequence[Mark], retain: bool) -> None:
197
+ if not marks:
198
+ return
199
+ groups: Dict[Tuple[int, str, str], List[int]] = {}
200
+ for m in marks:
201
+ groups.setdefault((m.component, m.encoded, m.label), []).append(m.step)
202
+ out.write("\nMarks (%d, %d distinct):\n" % (len(marks), len(groups)))
203
+ for (comp, string, label), steps in groups.items():
204
+ out.write(" [%s] component %d: %s (steps %s)\n" % (label, comp + 1, string, ", ".join(map(str, steps))))
205
+ if not retain:
206
+ out.write(" (run with --trace-marks to see how each was derived)\n")
207
+
208
+
209
+ def _progress_line(sim: Simulator, started: float) -> str:
210
+ sizes = ",".join(str(len(c)) for c in sim.cur)
211
+ return "step %d: strings per component [%s], candidates %d, history %d, retained %d, elapsed %.2fs\n" % (
212
+ sim.step_no,
213
+ sizes,
214
+ sim.last_candidates,
215
+ sim.hist_count,
216
+ sim.retained_count,
217
+ time.perf_counter() - started,
218
+ )
219
+
220
+
221
+ def run_cli(args: "argparse.Namespace", out: Output, stdin: Any) -> int:
222
+ interactive = args.interactive
223
+ input_file = args.input_file
224
+ if input_file is None:
225
+ out.write("Enter input file name: ")
226
+ out.flush()
227
+ line = stdin.readline()
228
+ if not line:
229
+ raise GcrsimError("no input file given")
230
+ input_file = line.rstrip("\r\n")
231
+ run_steps = 0
232
+ if args.steps is not None:
233
+ if interactive:
234
+ raise GcrsimError("-i and a number of steps exclude each other")
235
+ try:
236
+ run_steps = int(args.steps)
237
+ except ValueError:
238
+ raise GcrsimError("Bad number of steps: %s !" % args.steps)
239
+ if run_steps < 0:
240
+ raise GcrsimError("Bad number of steps: %d !" % run_steps)
241
+ layout = args.format
242
+ human = layout in ("text", "perl") # the formats written by this module (the others are in listing.py)
243
+ if interactive and not human:
244
+ raise GcrsimError("-i works with --format text or perl only")
245
+ try:
246
+ sep = listing.separator(args.csv_sep)
247
+ except ValueError as exc:
248
+ raise GcrsimError(str(exc))
249
+ if not os.path.exists(input_file):
250
+ raise GcrsimError("Bad input filename: %s !" % input_file)
251
+
252
+ model = parse_model_file(input_file)
253
+ trace_target = model.lexicon.encode(args.trace) if args.trace is not None else None
254
+ settings = resolve_config(model, args.config)
255
+ if args.python_filter:
256
+ if not os.path.isfile(args.python_filter):
257
+ raise GcrsimError("Python filter file not found: %s" % args.python_filter)
258
+ apply_settings(settings, read_config_data(args.python_filter, True), args.python_filter)
259
+ settings.config_name += " + " + args.python_filter
260
+ if args.steps is None and not interactive:
261
+ if settings.steps is None: # the number of steps may come from the configuration
262
+ raise GcrsimError("no number of steps: give it after the model, set `steps` in the configuration, or use -i")
263
+ run_steps = settings.steps
264
+ if settings.print_sep and model.lexicon.has_lexemes:
265
+ lex, psep = model.lexicon, settings.print_sep
266
+ decode: Optional[Callable[[str], str]] = lambda text: lex.decode_spaced(text, psep)
267
+ else:
268
+ decode = model.lexicon.decode if model.lexicon.active else None
269
+ plain = decode or (lambda text: text)
270
+ if human:
271
+ out.decode = decode
272
+ say: Any = out
273
+ fmt: Any = None
274
+ else: # csv, jsonl: the data are written already decoded; what is not data goes to the format
275
+ out.decode = None
276
+ fmt = (listing.Jsonl(out.write, plain, sys.stderr.write) if args.format == "jsonl"
277
+ else listing.Csv(out.write, plain, sys.stderr.write, sep))
278
+ say = _LineSink(fmt.text)
279
+ sys.stdout = say # callbacks that print() end up in the same place as the marks
280
+ if args.trace is not None and not (1 <= args.component <= model.ncomp):
281
+ raise GcrsimError("--component must be between 1 and %d" % model.ncomp)
282
+ if args.stop_on_found and args.trace is None:
283
+ raise GcrsimError("--stop-on-found needs --trace STRING")
284
+ retain = args.trace is not None or bool(args.trace_marks) or bool(args.trace_mark_label)
285
+ trace_labels = set(args.trace_mark_label) # empty: derivations for every mark
286
+ stop_labels = set(args.stop_on_mark_label)
287
+ fail_labels = set(args.fail_on_mark)
288
+ sim = Simulator(
289
+ model,
290
+ settings,
291
+ write=say.write,
292
+ streaming=args.streaming,
293
+ retain=retain or interactive,
294
+ max_step_candidates=args.max_step_candidates,
295
+ max_history=args.max_history,
296
+ max_step_accepted=args.max_step_accepted,
297
+ max_retained=args.max_retained,
298
+ max_marks=args.max_marks,
299
+ trace_best_effort=args.trace_best_effort,
300
+ no_mark_rejected=args.no_mark_rejected,
301
+ retain_store=SqliteRetention(args.retain_file) if (retain and args.retain_file) else None,
302
+ )
303
+ verifier = Verifier(sim) if args.cross_check else None
304
+ skip = make_matcher(settings.print_hide, model.lexicon)
305
+ plen: Optional[int] = settings.print_max_len
306
+ if args.print_all:
307
+ skip, plen = None, None
308
+ quiet = args.quiet and human
309
+ started = time.perf_counter()
310
+
311
+ if not human:
312
+ fmt.start(__version__, input_file, settings.config_name, sim.cur, skip, plen, settings.description)
313
+ elif not quiet:
314
+ if layout == "perl":
315
+ _header(out, input_file, settings, sim.has_filter)
316
+ _print_conf(out, sim.cur, skip, plen)
317
+ else:
318
+ _text_header(out, input_file, settings, model)
319
+ out.write("step 0\n")
320
+ _print_text_conf(out, sim.cur, skip, plen)
321
+ out.flush()
322
+
323
+ trace_found = False
324
+ trace_comp = args.component - 1
325
+
326
+ def check_trace() -> bool:
327
+ """Report the derivation the first time the traced string is in its content."""
328
+ nonlocal trace_found
329
+ if args.trace is None or trace_found or trace_target not in sim.cur[trace_comp]:
330
+ return False
331
+ trace_found = True
332
+ say.write(
333
+ "\nTrace of %r (component %d), first appearing at step %d:\n" % (args.trace, args.component, sim.step_no)
334
+ )
335
+ try:
336
+ say.write(format_derivation(sim._trace_many([(trace_comp, trace_target, sim.step_no)])[0]))
337
+ except TraceError as exc: # e.g. retention was exhausted with --trace-best-effort
338
+ say.write(" (derivation unavailable: %s)\n" % exc)
339
+ return True
340
+
341
+ shown_marks = 0
342
+ step = 1
343
+
344
+ def run_one_step() -> bool:
345
+ """Do one step and print it; True if a stop option asks to end the run after it."""
346
+ nonlocal shown_marks, step
347
+ if human and not quiet:
348
+ out.write("\n\n============\nSTEP %d\n============\n\n" % step if layout == "perl" else "step %d\n" % step)
349
+ step += 1
350
+ sim.step()
351
+ if verifier is not None:
352
+ verifier.check_step()
353
+ if not human:
354
+ fmt.step(sim.step_no, sim.cur, skip, plen)
355
+ elif not quiet:
356
+ (_print_conf if layout == "perl" else _print_text_conf)(out, sim.cur, skip, plen)
357
+ new_marks = sim.marks[shown_marks:]
358
+ shown_marks = len(sim.marks)
359
+ _print_marks_block(say, sim, [m for m in new_marks if not trace_labels or m.label in trace_labels], retain)
360
+ check_trace()
361
+ out.flush()
362
+ if args.progress:
363
+ sys.stderr.write(_progress_line(sim, started))
364
+ sys.stderr.flush()
365
+ return bool(
366
+ (args.stop_on_found and trace_found)
367
+ or (args.stop_on_mark and new_marks)
368
+ or (stop_labels and any(m.label in stop_labels for m in new_marks))
369
+ )
370
+
371
+ def _mark_shown() -> None:
372
+ nonlocal shown_marks
373
+ shown_marks = len(sim.marks)
374
+
375
+ check_trace() # the string may already be an axiom (step 0)
376
+ status = 0
377
+ try:
378
+ if interactive:
379
+ session = stepper.Session(sim, out, stdin, skip, plen, layout, _mark_shown, lambda: _print_marks_summary(out, sim.marks, True))
380
+ if not (args.stop_on_found and trace_found):
381
+ while True:
382
+ count = session.next_count()
383
+ if count == 0:
384
+ break
385
+ stopped = False
386
+ for _ in range(count):
387
+ if run_one_step():
388
+ stopped = True
389
+ break
390
+ if stopped:
391
+ break
392
+ else:
393
+ run_loop = run_steps > 0 and not (args.stop_on_found and trace_found)
394
+ while run_loop:
395
+ if run_one_step():
396
+ break
397
+ if run_steps < step:
398
+ break
399
+ if not args.run_empty and not any(sim.cur):
400
+ sys.stderr.write("gcrsim: no strings remain at step %d; stopping (use --run-empty to continue)\n" % sim.step_no)
401
+ break
402
+ except LimitReached as exc:
403
+ out.flush()
404
+ sys.stderr.write("gcrsim: %s\n" % out.text(str(exc)))
405
+ status = exc.exit_code
406
+ except KeyboardInterrupt:
407
+ out.flush()
408
+ sys.stderr.write("gcrsim: interrupted during step %d; output of that step may be partial\n" % step)
409
+ status = 130
410
+ if verifier is not None and status == 0:
411
+ sys.stderr.write("gcrsim: verified %d step(s) against the reference interpreter\n" % verifier.steps)
412
+ if args.trace is not None and not trace_found and status == 0:
413
+ say.write("\nTrace of %r (component %d): not found in the steps run\n" % (args.trace, args.component))
414
+ if not quiet and not args.no_mark_summary:
415
+ _print_marks_summary(say, sim.marks, retain or interactive)
416
+ if not human:
417
+ say.flush()
418
+ out.flush()
419
+ if fail_labels and status == 0:
420
+ failing = [m for m in sim.marks if "*" in fail_labels or m.label in fail_labels]
421
+ if failing:
422
+ sys.stderr.write(
423
+ "gcrsim: check failed: %d mark(s) with label(s) %s (first: step %d, component %d, %r)\n"
424
+ % (len(failing), ", ".join(sorted({m.label for m in failing})), failing[0].step,
425
+ failing[0].component + 1, model.lexicon.decode(failing[0].encoded))
426
+ )
427
+ status = CHECK_FAILED_STATUS
428
+ if not human:
429
+ fmt.end(sim.step_no, status)
430
+ out.flush()
431
+ return status
432
+
433
+
434
+ def main(argv: Optional[Sequence[str]] = None) -> int:
435
+ """Command line entry point; returns the process exit status."""
436
+ if argv is None:
437
+ argv = sys.argv[1:]
438
+ args = _build_parser().parse_args(argv)
439
+ for stream in (sys.stderr,):
440
+ try:
441
+ stream.reconfigure(errors="backslashreplace")
442
+ except (AttributeError, ValueError):
443
+ pass
444
+ real_stdout = sys.stdout
445
+ out = Output(real_stdout)
446
+ sys.stdout = out # callbacks that print() stay in order with simulator output
447
+ try:
448
+ return run_cli(args, out, sys.stdin)
449
+ except GcrsimError as exc:
450
+ out.flush()
451
+ sys.stderr.write("gcrsim: %s\n" % out.text(str(exc)))
452
+ return exc.exit_code
453
+ except BrokenPipeError:
454
+ _silence_stdout()
455
+ return 1
456
+ except KeyboardInterrupt:
457
+ try:
458
+ out.flush()
459
+ except BrokenPipeError:
460
+ pass
461
+ sys.stderr.write("gcrsim: interrupted\n")
462
+ return 130
463
+ finally:
464
+ try:
465
+ out.flush()
466
+ except BrokenPipeError:
467
+ _silence_stdout()
468
+ finally:
469
+ sys.stdout = real_stdout
470
+
471
+
472
+ def _silence_stdout() -> None:
473
+ """After a closed pipe, point stdout at the null device (no exit-time error)."""
474
+ try:
475
+ devnull = os.open(os.devnull, os.O_WRONLY)
476
+ os.dup2(devnull, sys.__stdout__.fileno())
477
+ except (OSError, ValueError, AttributeError):
478
+ pass