specla 0.0.1__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.
specla/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Specla: load, lint and evaluate a Specla Behavior."""
2
+
3
+ __version__ = "0.0.1"
specla/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from specla.cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,30 @@
1
+ """The Behavior: a document, read and checked against its schema. The lint is `specla.behavior.lint`."""
2
+ from functools import cache
3
+ from importlib.resources import files
4
+ from pathlib import Path
5
+
6
+ import yaml
7
+ from jsonschema import Draft202012Validator
8
+
9
+ VERSION = "behavior/0.1"
10
+ SCHEMA = files("specla") / "schemas" / "behavior" / "0.1" / "behavior.schema.yaml"
11
+
12
+
13
+ @cache
14
+ def validator() -> Draft202012Validator:
15
+ schema = yaml.safe_load(SCHEMA.read_text())
16
+ Draft202012Validator.check_schema(schema)
17
+ return Draft202012Validator(schema)
18
+
19
+
20
+ def schema_errors(document) -> list[str]:
21
+ """Each way the document departs from the schema, as `path: message`, in document order: findings of
22
+ the code `schema`. Empty when it fits."""
23
+ from specla.behavior.findings import Finding
24
+ errors = sorted(validator().iter_errors(document), key=lambda e: [str(p) for p in e.absolute_path])
25
+ return [Finding("schema", e.absolute_path,
26
+ f"{'/'.join(str(p) for p in e.absolute_path) or '(top)'}: {e.message}") for e in errors]
27
+
28
+
29
+ def load(path: Path):
30
+ return yaml.safe_load(Path(path).read_text())
@@ -0,0 +1,344 @@
1
+ """Examples checked against requirements: each example is read whole and every requirement on its action is evaluated
2
+ on it.
3
+
4
+ An example states only what differs: its `pre` from the defaults, its `post` from its `pre`. Read whole, it gives the
5
+ two snapshots, the inputs and the outputs. Each record the action is `about` is then found in each snapshot by its
6
+ key, and each requirement on the action is judged: where its `assume` holds, its `require` must. A requirement with no
7
+ action must hold in both snapshots.
8
+
9
+ The check is linear: each example, each requirement once. An answered ambiguity has one reading, and a requirement
10
+ that reads it is judged under that reading. An open ambiguity is not tried under its readings here:
11
+
12
+ - a requirement that calls, at any depth, a calculation an open ambiguity gives the result of is not judged, and a
13
+ note says so;
14
+ - the clauses an open ambiguity's readings add to a requirement are not judged, and a note says so; the requirement's
15
+ own clauses, which hold under every reading, are.
16
+
17
+ Each example is evaluated within a budget of steps (`BUDGET`), and the document's examples together within another
18
+ (`TOTAL`), so a document too large to evaluate gets a note for each example left unchecked, never an answer it did
19
+ not finish. A step is one node of an expression evaluated, about a microsecond; the largest example seen in practice
20
+ takes a few thousand.
21
+
22
+ Run it on a document the lint passes.
23
+ """
24
+ import copy
25
+ from dataclasses import dataclass, field
26
+
27
+ from specla.behavior import expression as ex
28
+ from specla.behavior.findings import Finding, Locator, Where
29
+ from specla.behavior.model import Model, is_many, lower_camel
30
+
31
+ RECORD_KEY, TYPE_KEY = "record", ex.TYPE_KEY
32
+ BUDGET = 1_000_000 # steps for one example; past it, the example is noted as not checked
33
+ TOTAL = 20_000_000 # steps for every example of a document; past it, each example left is noted
34
+
35
+
36
+ class Unstated(Exception):
37
+ """An example leaves unsaid something with no default: the finding that says so."""
38
+
39
+ def __init__(self, finding: Finding):
40
+ super().__init__(str(finding))
41
+ self.finding = finding
42
+
43
+
44
+ def _where(where: str) -> Where:
45
+ """A label with its location; a bare label is at no known location."""
46
+ return where if isinstance(where, Where) else Where(where, ())
47
+
48
+
49
+ class Reader:
50
+ """Reads stated values whole."""
51
+
52
+ def __init__(self, model: Model):
53
+ self.m = model
54
+
55
+ def record(self, item_def: str, stated: dict | None, where: str, base: dict | None = None) -> dict:
56
+ """One record whole: `base` (the record before, for a `post`), else the item def's defaults; then the named
57
+ record it cites; then what it states. Says which item def it is."""
58
+ m, stated, where = self.m, dict(stated or {}), _where(where)
59
+ actual = stated.pop(TYPE_KEY, None)
60
+ cited = stated.pop(RECORD_KEY, None)
61
+ named = m.named_records.get(cited) if cited else None
62
+ actual = actual or (named["type"] if named else None) or (base or {}).get(TYPE_KEY) or item_def
63
+ decls = m.feature_decls(actual)
64
+ if base is not None and base.get(TYPE_KEY, actual) == actual:
65
+ out = copy.deepcopy(base)
66
+ else:
67
+ out = {}
68
+ for name, decl in decls.items():
69
+ if decl["kind"] == "item":
70
+ out[name] = [] if is_many(decl["multiplicity"]) else None
71
+ elif "default" in decl:
72
+ out[name] = copy.deepcopy(decl["default"])
73
+ elif is_many(decl.get("multiplicity")):
74
+ out[name] = []
75
+ if actual in m.item_defs:
76
+ out[TYPE_KEY] = actual
77
+ for layer, layer_where in ((named["values"] if named else {}, Where(f"named record {cited}", where.loc)),
78
+ (stated, where)):
79
+ for name, value in layer.items():
80
+ out[name] = self.value(decls[name], value, layer_where.key(name), out.get(name))
81
+ missing = [name for name in decls if name not in out]
82
+ if missing:
83
+ raise Unstated(Finding("example-unstated", where.loc, f"{where}: {', '.join(missing)} of {actual} {'is' if len(missing) == 1 else 'are'} not "
84
+ f"stated and {'has' if len(missing) == 1 else 'have'} no default"))
85
+ return out
86
+
87
+ def value(self, decl: dict, value, where: str, before=None):
88
+ """One feature's or parameter's value whole. A stated list replaces the list before; a stated record of at
89
+ most one is read as what differs from the record before."""
90
+ if decl["type"] not in self.m.item_defs:
91
+ return copy.deepcopy(value)
92
+ if is_many(decl.get("multiplicity")):
93
+ return [self.record(decl["type"], v, where.item(i)) for i, v in enumerate(value)]
94
+ return None if value is None else self.record(decl["type"], value, where,
95
+ before if isinstance(before, dict) else None)
96
+
97
+ def snapshot(self, stated: dict | None, where: str, base: dict | None = None) -> dict:
98
+ return self.record(self.m.subject["name"], stated, where, base)
99
+
100
+ def parameters(self, action: dict, direction: str, stated: dict | None, where: str) -> dict:
101
+ params, where = {p["name"]: p for p in action.get(direction, [])}, _where(where)
102
+ return {name: self.value(params[name], v, where.key(name)) for name, v in (stated or {}).items()}
103
+
104
+
105
+ def bind_about(model: Model, action: dict, requirement: dict | None, snapshot: dict, params: dict, where: Where,
106
+ example: tuple = ()):
107
+ """The snapshot with each `about` name added: the record of the set whose key equals the key expression, or null.
108
+ Returns (snapshot, errors). `where` is the snapshot, `example` where its example is."""
109
+ out, errors, where = dict(snapshot), [], _where(where)
110
+ for name, entry in model.about(action, requirement).items():
111
+ t = model.about_type(entry)
112
+ key_attr = model.key_of(t.base) if t else None
113
+ try:
114
+ key = ex.Evaluator(null_safe=True).value(entry["key"], params)
115
+ except ex.EvaluationError as error:
116
+ errors.append(Finding("about-unfound", example, f"{where}: `about` {name} cannot be found: {error}"))
117
+ out[name] = None
118
+ continue
119
+ held = snapshot.get(entry["of"])
120
+ held = held if isinstance(held, list) else [] if held is None else [held]
121
+ found = [] if key is None else [r for r in held if ex.equal(r.get(key_attr), key)] # a null key names none
122
+ if len(found) > 1:
123
+ errors.append(Finding("key-duplicate", where.loc + (entry["of"],),
124
+ f"{where}: {len(found)} records of `{entry['of']}` have {key_attr} {key!r}"))
125
+ out[name] = found[0] if found else None
126
+ return out, errors
127
+
128
+
129
+ def key_errors(model: Model, snapshot: dict, where: Where) -> list[str]:
130
+ """A set whose item def names a key holds no two records with one key."""
131
+ out, where = [], _where(where)
132
+ for name, decl in model.feature_decls(model.subject["name"]).items():
133
+ key = model.key_of(decl["type"]) if decl["kind"] == "item" else None
134
+ if not key or not isinstance(snapshot.get(name), list):
135
+ continue
136
+ keys = [r.get(key) for r in snapshot[name]]
137
+ for k in dict.fromkeys(k for k in keys if keys.count(k) > 1):
138
+ out.append(Finding("key-duplicate", where.loc + (name,),
139
+ f"{where}: `{name}` holds two records with {key} {k!r}"))
140
+ return out
141
+
142
+
143
+ def open_reads(model: Model, requirement: dict) -> tuple[tuple[str, ...], tuple[str, ...]]:
144
+ """(through calculations, adding clauses): the open ambiguities a requirement reads, in document order. The first
145
+ give the result of a calculation it calls, at any depth, so it cannot be judged without choosing a reading; the
146
+ second add clauses to it, which are left out, its own clauses being judged."""
147
+ ambiguities = model.doc.get("ambiguities", [])
148
+ open_ids = {a["id"] for a in model.open_ambiguities()}
149
+ about = {}
150
+ for a in ambiguities:
151
+ if "about" in a:
152
+ about.setdefault(a["about"], []).append(a)
153
+ adding = tuple(a["id"] for a in ambiguities if a["id"] in open_ids and requirement["id"] in a.get("appliesTo", []))
154
+ found = set()
155
+ seen, todo = set(), [c for text in requirement.get("assume", []) + requirement.get("require", [])
156
+ for c in ex.calls(ex.parse(text))]
157
+ while todo:
158
+ name = todo.pop()
159
+ if name in seen:
160
+ continue
161
+ seen.add(name)
162
+ calc = model.calculations.get(name) or {}
163
+ results = [calc["result"]] if calc.get("result") else []
164
+ for a in about.get(name, []):
165
+ found.add(a["id"])
166
+ results += [r["result"] for r in a["readings"] if r.get("result")]
167
+ todo += [c for text in results for c in ex.calls(ex.parse(text))]
168
+ through = tuple(a["id"] for a in ambiguities if a["id"] in found and a["id"] in open_ids)
169
+ return through, adding
170
+
171
+
172
+ def _evaluator(model: Model) -> tuple[ex.Evaluator, dict[str, list[str]]]:
173
+ """The evaluator with each calculation's result, an answered ambiguity's reading in place of an open calculation's,
174
+ and the clauses each answered ambiguity's reading adds, by requirement."""
175
+ results = {c["name"]: c.get("result") for c in model.doc.get("calculations", [])}
176
+ extra: dict[str, list[str]] = {}
177
+ for amb in model.doc.get("ambiguities", []):
178
+ if amb["status"] == "open":
179
+ continue
180
+ reading = next((r for r in amb["readings"] if r["name"] == amb.get("answer")), None)
181
+ if reading is None:
182
+ continue
183
+ if "about" in amb:
184
+ results[amb["about"]] = reading["result"]
185
+ else:
186
+ for req_id in amb["appliesTo"]:
187
+ extra.setdefault(req_id, []).extend(reading["require"])
188
+ calculations = {c["name"]: ([p["name"] for p in c.get("in", [])],
189
+ ex.parse(results[c["name"]]) if results[c["name"]] else None)
190
+ for c in model.doc.get("calculations", [])}
191
+ return ex.Evaluator(calculations, model.specializes), extra
192
+
193
+
194
+ def check_examples(doc, budget: int | None = BUDGET, total: int | None = TOTAL) -> tuple[list[str], list[str]]:
195
+ """(errors, notes). An error: an example that cannot be read whole; one a requirement it was judged on does not
196
+ hold in; one that does not meet the `assume` of a requirement it illustrates; a query's example whose snapshot
197
+ changes. A note: a requirement left unjudged because it reads an open ambiguity, with the examples it was left
198
+ unjudged on; the clauses an open ambiguity adds, left out; an example over its budget; the examples left once the
199
+ document's budget is spent."""
200
+ checker = Checker(doc, budget)
201
+ errors, skipped, spent, unchecked = [], {}, [], []
202
+ left = total
203
+ for example in doc.get("examples", []):
204
+ if left is not None and left <= 0:
205
+ unchecked.append((example["id"], "budget"))
206
+ continue
207
+ own = budget if left is None or (budget is not None and budget <= left) else left
208
+ checker.budget = own
209
+ judged = checker.judge(example)
210
+ if left is not None:
211
+ left -= judged.steps
212
+ if judged.spent:
213
+ (spent if own == budget or judged.spent == "depth" else unchecked).append((example["id"], judged.spent))
214
+ continue
215
+ errors.extend(judged.errors)
216
+ for rid in judged.skipped:
217
+ skipped.setdefault(rid, []).append(example["id"])
218
+ notes, at = [], checker.at
219
+ for rid, examples in skipped.items():
220
+ notes.append(Finding("requirement-unjudged", at(checker.model.requirements[rid]),
221
+ f"{rid} is not judged on {', '.join(examples)}: it reads "
222
+ f"{_listed(checker.reads[rid][0])}, open, through a calculation"))
223
+ for amb in doc.get("ambiguities", []):
224
+ if amb["status"] == "open" and amb.get("appliesTo") and doc.get("examples"):
225
+ notes.append(Finding("clauses-unjudged", at(amb),
226
+ f"the clauses {amb['id']}'s readings add to {', '.join(amb['appliesTo'])} are not "
227
+ f"judged: {amb['id']} is open"))
228
+ by_id = {e["id"]: e for e in doc.get("examples", [])}
229
+ notes += [Finding("example-over-budget", at(by_id[eid]), f"example {eid} is not checked: its evaluation "
230
+ + (f"took more than {budget:,} steps" if why == "budget" else "went too deep: a calculation "
231
+ "that calls itself without end?")) for eid, why in spent]
232
+ if unchecked:
233
+ ids = [eid for eid, _ in unchecked]
234
+ notes.append(Finding("examples-over-budget", (), f"{_listed(ids)} {'is' if len(ids) == 1 else 'are'} not "
235
+ f"checked: the document's examples took more than {total:,} steps together"))
236
+ return errors, notes
237
+
238
+
239
+ def _listed(ids) -> str:
240
+ return ids[0] if len(ids) == 1 else ", ".join(ids[:-1]) + " and " + ids[-1]
241
+
242
+
243
+ @dataclass
244
+ class Judged:
245
+ """One example against the requirements: its errors, the requirements on it left unjudged because they read an
246
+ open ambiguity (`open_reads`), and whether its budget was spent, in which case its errors are not given."""
247
+ errors: list[str]
248
+ skipped: list[str] = field(default_factory=list)
249
+ spent: str = "" # why it was not finished: `budget` or `depth`; empty where it was
250
+ steps: int = 0
251
+
252
+
253
+ class Checker:
254
+ """A Behavior's requirements, read once, to judge its examples one at a time: each of the document's, or one
255
+ changed by hand (a stated value changed, and the example judged again)."""
256
+
257
+ def __init__(self, doc, budget: int | None = BUDGET):
258
+ self.model = Model(doc)
259
+ self.at = Locator(doc).of
260
+ self.reader = Reader(self.model)
261
+ self.budget = budget
262
+ self.evaluator, self.extra = _evaluator(self.model)
263
+ self.subject_var = lower_camel(self.model.subject["name"])
264
+ self.always = [r for r in self.model.requirements_on(None) if not self.model.is_informal(r)]
265
+ self.reads = {r["id"]: open_reads(self.model, r) for r in doc.get("requirements", [])
266
+ if not self.model.is_informal(r)}
267
+
268
+ def judge(self, example: dict) -> Judged:
269
+ model, reader = self.model, self.reader
270
+ label, here = f"example {example['id']}", self.at(example)
271
+ where = {key: Where(f"{label} {key}", here + (key,)) for key in ("pre", "post", "in", "out")}
272
+ action = model.actions[example["action"]]
273
+ try:
274
+ pre = reader.snapshot(example.get("pre"), where["pre"])
275
+ post = reader.snapshot(example.get("post"), where["post"], base=pre)
276
+ params = {**reader.parameters(action, "in", example.get("in"), where["in"]),
277
+ **reader.parameters(action, "out", example.get("out"), where["out"])}
278
+ except Unstated as error:
279
+ return Judged([error.finding])
280
+ found = key_errors(model, pre, where["pre"]) + key_errors(model, post, where["post"])
281
+ if action["kind"] == "query" and not ex.equal(pre, post):
282
+ found.append(Finding("query-changes", here + ("post",),
283
+ f"{label}: `{action['name']}` is a query, and its `post` differs from its `pre`"))
284
+ if found:
285
+ return Judged(found)
286
+ on_action = [r for r in model.requirements_on(action["name"]) if not model.is_informal(r)]
287
+ errors, skipped, applied = [], [], set()
288
+ self.evaluator.budget(self.budget)
289
+ try:
290
+ for snapshot, which in ((pre, "pre"), (post, "post")):
291
+ for r in self.always:
292
+ if self.reads[r["id"]][0]:
293
+ skipped.append(r["id"])
294
+ continue
295
+ said = self._judge(r, {self.subject_var: snapshot})
296
+ if said not in (True, None):
297
+ errors.append(Finding("invariant-violated", here + (which,),
298
+ f"{label}: {r['id']} does not hold in its {which}: {said}",
299
+ [self.at(r)]))
300
+ for r in on_action:
301
+ pre_bound, e1 = bind_about(model, action, r, pre, params, where["pre"], here)
302
+ post_bound, e2 = bind_about(model, action, r, post, params, where["post"], here)
303
+ errors += [e.prefixed(f"{label}: ") for e in e1 + e2]
304
+ if e1 or e2: # a record it is about cannot be found: said once, and it is not judged
305
+ continue
306
+ if self.reads[r["id"]][0]:
307
+ skipped.append(r["id"])
308
+ continue
309
+ said = self._judge(r, {"pre": pre_bound, "post": post_bound, lower_camel(action["name"]): params})
310
+ if said is not None:
311
+ applied.add(r["id"])
312
+ if said not in (True, None):
313
+ errors.append(Finding("requirement-violated", here,
314
+ f"{label}: {r['id']} applies and does not hold: {said}", [self.at(r)]))
315
+ except ex.BudgetSpent:
316
+ return Judged([], spent="budget", steps=self.budget or 0)
317
+ except RecursionError: # a calculation that calls itself without end, before the budget is spent
318
+ return Judged([], spent="depth", steps=self.budget or 0)
319
+ finally:
320
+ steps = 0 if self.budget is None else self.budget - max(self.evaluator.steps_left, 0)
321
+ self.evaluator.budget(None)
322
+ if errors:
323
+ return Judged(list(dict.fromkeys(errors)), list(dict.fromkeys(skipped)), steps=steps)
324
+ for n, req_id in enumerate(example.get("illustrates", [])):
325
+ r = model.requirements[req_id]
326
+ if (r.get("action") and not model.is_informal(r) and req_id not in applied
327
+ and req_id not in skipped):
328
+ errors.append(Finding("illustrates-unmet", here + ("illustrates", n),
329
+ f"{label}: illustrates {req_id}, whose `assume` it does not meet"))
330
+ return Judged(list(dict.fromkeys(errors)), list(dict.fromkeys(skipped)), steps=steps)
331
+
332
+ def _judge(self, requirement: dict, env: dict):
333
+ """True where the requirement holds, None where its `assume` does not apply, else why it does not hold."""
334
+ evaluator = self.evaluator
335
+ try:
336
+ for text in requirement.get("assume", []):
337
+ if not evaluator.holds(text, env):
338
+ return None
339
+ for text in requirement.get("require", []) + self.extra.get(requirement["id"], []):
340
+ if not evaluator.holds(text, env):
341
+ return f"`{text}` is false"
342
+ except ex.EvaluationError as error:
343
+ return f"`{text}` cannot be evaluated: {error}"
344
+ return True
@@ -0,0 +1,39 @@
1
+ # Design words: a name in a Behavior that uses one is a warning, unless the intent itself uses the word. A Behavior
2
+ # says what the subject must do, seen from outside; these words say how it is built. One word per line, lower case.
3
+ adapter
4
+ cache
5
+ cached
6
+ class
7
+ client
8
+ column
9
+ controller
10
+ database
11
+ db
12
+ dao
13
+ dto
14
+ entity
15
+ handler
16
+ impl
17
+ index
18
+ lock
19
+ manager
20
+ middleware
21
+ module
22
+ mutex
23
+ orm
24
+ port
25
+ queue
26
+ repo
27
+ repository
28
+ router
29
+ row
30
+ schema
31
+ server
32
+ service
33
+ sql
34
+ storage
35
+ store
36
+ table
37
+ thread
38
+ transaction
39
+ worker