Repository navigation
Expand file tree
/
Copy pathcomparison.py
More file actions
1496 lines (1397 loc) · 49.2 KB
/
Copy pathcomparison.py
File metadata and controls
1496 lines (1397 loc) · 49.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Declare one symbolic method and bind comparison tables to captured cases."""
from __future__ import annotations
import ast
import builtins
import math
from .function_calls import FUNCTION_CALLS
import hashlib
from pathlib import Path
from .annotations import symbol_annotation
from .source import Json, SourceError, authoring_name, compact, identity, kwargs, span
from .source_plan import _describe_call, lower_expression
_NUMERIC_CALLS = {
call.function_id: getattr(math if call.module == "math" else builtins, call.name)
for call in FUNCTION_CALLS
}
_OPERATORS = {
"fg.add": "+",
"fg.subtract": "-",
"fg.multiply": "*",
"fg.divide": "/",
"fg.pow": "^",
}
_COMPARISONS = {
"fg.lt": "<",
"fg.le": "<=",
"fg.gt": ">",
"fg.ge": ">=",
"fg.eq": "==",
"fg.ne": "!=",
}
def place_comparison(
planner, inv, statement: ast.Expr, section: Json, ids: set[str]
) -> None:
call = statement.value
if not isinstance(call, ast.Call):
return
name = authoring_name(call.func)
if name not in {"method", "table"}:
return
if name not in inv.module.imported:
planner.error(inv, call, "UNSUPPORTED_SYNTAX", "Unimported authoring helper")
if name == "method":
_place_method(planner, inv, call, section, ids)
else:
_place_table(planner, inv, call, section, ids)
def _keywords(planner, inv, call: ast.Call) -> dict[str, ast.keyword]:
if call.args or any(keyword.arg is None for keyword in call.keywords):
planner.error(
inv,
call,
"INVALID_METHOD",
"Method and table declarations use explicit named arguments",
)
found: dict[str, ast.keyword] = {}
for keyword in call.keywords:
if keyword.arg in found:
planner.error(
inv,
keyword,
"INVALID_METHOD",
f"Duplicate keyword {keyword.arg!r}",
)
found[keyword.arg] = keyword
return found
def _require(
planner, inv, found: dict[str, ast.keyword], allowed: set[str], required: set[str]
) -> None:
unknown = found.keys() - allowed
missing = required - found.keys()
if unknown or missing:
planner.error(
inv,
next(iter(found.values()), inv.function),
"INVALID_METHOD",
f"Unknown keywords {sorted(unknown)}; missing keywords {sorted(missing)}",
)
def _text(planner, inv, keyword: ast.keyword) -> str:
value = keyword.value
if (
not isinstance(value, ast.Constant)
or not isinstance(value.value, str)
or not value.value
):
planner.error(
inv,
keyword,
"INVALID_METHOD",
f"{keyword.arg} must be a nonempty literal string",
)
return value.value
def _place_method(planner, inv, call: ast.Call, section: Json, ids: set[str]) -> None:
found = _keywords(planner, inv, call)
_require(
planner,
inv,
found,
{"id", "calculation", "title"},
{"id", "calculation", "title"},
)
local_id = _text(planner, inv, found["id"])
title = _text(planner, inv, found["title"])
method_id = identity("method", inv.id, local_id)
if method_id in ids or (inv.id, local_id) in planner.method_index:
planner.error(
inv, call, "DUPLICATE_IDENTITY", "Duplicate method or table identity"
)
handle_name = found["calculation"].value
if (
not isinstance(handle_name, ast.Name)
or handle_name.id not in inv.module.handles
):
planner.error(
inv,
found["calculation"],
"INVALID_METHOD",
"method.calculation must name a calculation handle",
)
handle = inv.module.handles[handle_name.id]
target = planner.capture.load(handle["path"], span(inv.module.id, call))
function_name = handle["function"]
if function_name not in target.functions:
planner.error(
inv, call, "MISSING_FUNCTION", f"Missing calculation {function_name}"
)
_reject_deferred_content(planner, inv, target, function_name, call)
definition = planner.definitions.get(target.path, function_name)
if (
handle["fingerprint"] is not None
and handle["fingerprint"] != definition.fingerprint
):
planner.error(
inv,
call,
"STALE_BINDINGS",
"Run cso bindings to refresh the changed public interface",
)
plan = planner.ensure_plan(inv, target, function_name)
quantities = _quantities(planner, inv, target, definition, plan, call)
content, helpers, checks, applicability = _method_content(
planner,
inv,
target,
definition,
plan,
quantities,
method_id,
call,
{(target.id, function_name)},
{},
)
record = {
"id": method_id,
"localId": local_id,
"invocationId": inv.id,
"title": title,
"moduleId": target.id,
"function": function_name,
"sourceHash": plan.source_hash,
"interfaceFingerprint": plan.fingerprint,
"revision": _method_revision(plan.revision, content, helpers),
"parameterNames": list(definition.parameters),
"outputNames": list(definition.outputs),
"quantities": quantities,
"metadata": _section_metadata(target, definition.function),
"content": content,
"helpers": _unique_helpers(helpers, set()),
"location": span(inv.module.id, call),
}
if checks:
record["checks"] = checks
if applicability:
record["applicability"] = applicability
ids.add(method_id)
planner.method_index[(inv.id, local_id)] = record
planner.methods.append(record)
section["items"].append(
{
"kind": "method",
"id": method_id,
"metadata": planner.metadata(inv, local_id, call),
}
)
def _unique_helpers(helpers: list[Json], seen: set[str]) -> list[Json]:
"""Keep one definition when distinct call paths share a dependency."""
unique = []
for helper in helpers:
if helper["id"] in seen:
continue
seen.add(helper["id"])
unique.append({**helper, "helpers": _unique_helpers(helper["helpers"], seen)})
return unique
def _method_revision(revision: str, content: list[Json], helpers: list[Json]) -> str:
external = []
def walk(items):
for item in items:
if item["kind"] == "external":
external.append(item)
elif item["kind"] == "section":
walk(item["content"])
walk(content)
def visit(records):
for helper in records:
walk(helper["content"])
visit(helper["helpers"])
visit(helpers)
return (
hashlib.sha256(
compact({"sourcePlan": revision, "external": external}).encode()
).hexdigest()
if external
else revision
)
def _section_metadata(module, function: ast.FunctionDef) -> Json:
for decorator in function.decorator_list:
if (
isinstance(decorator, ast.Call)
and authoring_name(decorator.func) == "section"
):
config = kwargs(
decorator, module.id, {"id", "title", "root", "metadata"}, {"title"}
)
return config.get("metadata", {})
return {}
def _reject_deferred_content(
planner, inv, module, function_name: str, at: ast.AST
) -> None:
function = module.functions[function_name]
for node in ast.walk(ast.Module(body=function.body, type_ignores=[])):
if isinstance(node, ast.With) and not _is_document_section(node):
planner.error(
inv,
at,
"UNSUPPORTED_METHOD_CONTENT",
"Only document sections can group method content",
)
def _is_document_section(node: ast.AST) -> bool:
return (
isinstance(node, ast.With)
and len(node.items) == 1
and node.items[0].optional_vars is None
and isinstance(node.items[0].context_expr, ast.Call)
and authoring_name(node.items[0].context_expr.func) == "document_section"
)
def _quantities(planner, inv, module, definition, plan, at: ast.AST) -> list[Json]:
glyphs: dict[str, str] = {}
quantities: list[Json] = []
output_variables = {
output.selection.id: key
for key, output in definition.outputs.items()
if isinstance(output.selection, ast.Name)
}
for name, spec in definition.parameters.items():
if name in definition.given_parameters:
continue
metadata = spec.declared.metadata
if metadata is None:
planner.error(
inv,
at,
"UNDOCUMENTED_INPUT",
f"Parameter {name!r} needs symbol metadata",
)
glyphs[name] = metadata["glyph"]
quantities.append(_quantity(name, name, "input", "input", metadata, [], glyphs))
for quantity in plan.quantities:
variable = quantity["variableName"]
nodes = quantity["nodes"]
assignment = _declared_assignment(plan.steps, variable)
if not isinstance(assignment, ast.AnnAssign):
planner.error(
inv,
at,
"UNSUPPORTED_METHOD_CONTENT",
f"Missing declaration for {variable!r}",
)
metadata = symbol_annotation(assignment, module.id, module.aliases).metadata
if metadata is None:
planner.error(
inv, at, "INVALID_METHOD", f"Missing symbol metadata for {variable!r}"
)
given = next(
(
node.get("parameter")
for node in nodes
if node.get("mode") == "GIVEN_PARAMETER"
),
None,
)
if given is not None:
role = "input"
selection = given
elif variable in output_variables:
role = "output"
selection = output_variables[variable]
else:
role = "intermediate"
selection = variable
glyphs[variable] = metadata["glyph"]
quantities.append(
_quantity(
variable, selection, quantity["kind"], role, metadata, nodes, glyphs
)
)
# A public return can forward a parameter or a child output without a
# local assignment. Describe that selection, but keep the table bound to
# the original captured symbol through child.outputs.
represented = {
item["selectionName"] for item in quantities if item["role"] == "output"
}
occupied = {item["variableName"] for item in quantities}
for index, (name, output) in enumerate(definition.outputs.items()):
if name in represented:
continue
variable = f"__return_{index}"
while variable in occupied:
variable += "_"
occupied.add(variable)
nodes = [
{key: value for key, value in node.items() if key != "_ast"}
for node in lower_expression(
module,
definition.function,
set(definition.parameters),
output.selection,
given=False,
)
]
metadata = output.annotation.metadata
if metadata is None:
planner.error(
inv, at, "INVALID_METHOD", f"Output {name!r} needs symbol metadata"
)
quantities.append(
_quantity(variable, name, "formula", "output", metadata, nodes, glyphs)
)
inputs = {item["selectionName"] for item in quantities if item["role"] == "input"}
outputs = {item["selectionName"] for item in quantities if item["role"] == "output"}
if inputs != set(definition.parameters) or outputs != set(definition.outputs):
planner.error(
inv,
at,
"UNSUPPORTED_METHOD_CONTENT",
"A straight-line method must explain every public input and output",
)
return quantities
def _quantity(
variable: str,
selection: str,
kind: str,
role: str,
metadata: Json,
nodes: list[Json],
glyphs: dict[str, str],
) -> Json:
return {
"variableName": variable,
"localId": metadata.get("id", variable),
"kind": kind,
"role": role,
"selectionName": selection,
"glyph": metadata["glyph"],
"description": metadata["description"],
"unit": metadata["unit"],
"formulaText": _formula_text(nodes, glyphs),
"nodes": nodes,
}
def _formula_text(
nodes: list[Json], glyphs: dict[str, str], key: str | None = None
) -> str:
if not nodes:
return ""
by_key = {node["key"]: node for node in nodes}
def walk(node_key: str) -> str:
node = by_key[node_key]
mode = node["mode"]
if mode == "LITERAL":
return str(node.get("draft", node["literal"]["value"]))
if mode == "SYMBOL":
ref = node.get("ref") or {}
if ref.get("kind") == "output":
return f"{ref['call']}.{ref['output']}"
name = ref.get("name") or ref.get("output")
return glyphs.get(name, name or node_key)
if mode == "GIVEN_PARAMETER":
return glyphs.get(node["parameter"], node["parameter"])
if mode == "FUNCTION":
arguments = [argument["key"] for argument in node["funcArgs"]]
function_id = node["funcSpec"]["id"]
if function_id == "fg.cnd":
return f"({walk(arguments[1])} if {walk(arguments[0])} else {walk(arguments[2])})"
if function_id in {"fg.and", "fg.or"}:
joiner = " and " if function_id == "fg.and" else " or "
return f"({joiner.join(walk(argument) for argument in arguments)})"
comparison = _COMPARISONS.get(function_id)
if comparison and len(arguments) == 2:
return f"{walk(arguments[0])} {comparison} {walk(arguments[1])}"
rendered = [walk(argument) for argument in arguments]
operator = _OPERATORS.get(function_id)
if function_id == "fg.uminus":
return f"-{rendered[0]}"
if operator and len(rendered) == 2:
return f"({rendered[0]} {operator} {rendered[1]})"
return f"{function_id}({', '.join(rendered)})"
return ""
return walk(key or nodes[0]["key"])
def _method_content(
planner,
inv,
module,
definition,
plan,
quantities: list[Json],
owner_id: str,
at: ast.AST,
stack: set[tuple[str, str]],
cache: dict[tuple[str, str], Json],
) -> tuple[list[Json], list[Json], list[Json], list[Json]]:
glyphs = {
(
item["selectionName"] if item["role"] == "input" else item["variableName"]
): item["glyph"]
for item in quantities
}
for item in quantities:
glyphs.setdefault(item["variableName"], item["glyph"])
content: list[Json] = [
{"kind": "quantity", "variableName": name}
for name in definition.parameters
if name not in definition.given_parameters
]
helpers: list[Json] = []
checks: list[Json] = []
applicability: list[Json] = []
_walk_steps(
planner,
inv,
module,
definition,
glyphs,
content,
helpers,
owner_id,
plan.steps,
stack,
cache,
at,
checks,
applicability,
{item["variableName"] for item in quantities},
)
seen = _content_variables(content)
# Forwarded returns have no assignment placement in the source plan.
content.extend(
{"kind": "quantity", "variableName": item["variableName"]}
for item in quantities
if item["role"] == "output" and item["variableName"] not in seen
)
seen = _content_variables(content)
if any(item["variableName"] not in seen for item in quantities):
planner.error(
inv,
at,
"UNSUPPORTED_METHOD_CONTENT",
"Method content must include every explained quantity",
)
return content, helpers, checks, applicability
def _walk_steps(
planner,
inv,
module,
definition,
glyphs: dict[str, str],
content: list[Json],
helpers: list[Json],
owner_id: str,
steps,
stack: set[tuple[str, str]],
cache: dict[tuple[str, str], Json],
at: ast.AST,
checks: list[Json],
applicability: list[Json],
names: set[str],
) -> None:
for step in steps:
node = step.node
if isinstance(node, ast.Return):
continue
if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
content.append({"kind": "quantity", "variableName": node.target.id})
continue
if isinstance(node, ast.With):
if (
not _is_document_section(node)
or "document_section" not in module.imported
):
planner.error(
inv,
node,
"UNSUPPORTED_METHOD_CONTENT",
"Only document sections can group method content",
)
config = kwargs(
node.items[0].context_expr,
module.id,
{"id", "title", "metadata"},
{"id", "title"},
)
nested: list[Json] = []
_walk_steps(
planner,
inv,
module,
definition,
glyphs,
nested,
helpers,
owner_id,
step.child_steps or [],
stack,
cache,
at,
checks,
applicability,
names,
)
content.append(
{
"kind": "section",
"localId": config["id"],
"title": config["title"],
"metadata": config.get("metadata", {}),
"content": nested,
}
)
continue
described = _describe_call(node)
if described is not None:
if described.get("kind") == "external":
declaration_module = planner.capture.load(
module.path.parent / described["path"], span(module.id, node)
)
declaration = declaration_module.externals.get(described["function"])
if declaration is None:
planner.error(
inv,
node,
"INVALID_METHOD",
"External method leaf must resolve to a static declaration",
)
adapter = planner.capture.modules[declaration.path]
content.append(
{
"kind": "external",
"binding": described["binding"],
"callSite": span(module.id, node),
"declaration": {
"moduleId": declaration_module.id,
"name": declaration.name,
"fingerprint": declaration.fingerprint,
"location": span(declaration_module.id, declaration.node),
"interface": declaration.interface,
},
"declarationSourceHash": hashlib.sha256(
declaration_module.data
).hexdigest(),
"adapter": {
"moduleId": adapter.id,
"sha256": hashlib.sha256(adapter.data).hexdigest(),
"function": declaration.function,
},
"inputs": _call_formulas(module, definition, node, glyphs),
"outputs": list(declaration.outputs),
}
)
continue
helper = _helper(
planner, inv, module, described, owner_id, stack, cache, node
)
if not any(item["id"] == helper["id"] for item in helpers):
helpers.append(helper)
content.append(
{
"kind": "call",
"binding": described["binding"],
"helperId": helper["id"],
"inputs": _call_formulas(module, definition, node, glyphs),
"outputs": list(helper["outputNames"]),
}
)
continue
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
name = authoring_name(node.value.func)
if name in {"method", "table"}:
continue
if name == "text":
data = kwargs(
node.value, module.id, {"id", "content"}, {"id", "content"}
)
content.append(
{"kind": "text", "localId": data["id"], "content": data["content"]}
)
continue
if name in {"check", "applicable"}:
declared = _check_declaration(
planner,
inv,
module,
definition,
glyphs,
node.value,
names,
checks if name == "check" else applicability,
)
if name == "check":
checks.append(declared)
content.append({"kind": "check", "localId": declared["id"]})
else:
applicability.append(declared)
content.append({"kind": "applicability", "localId": declared["id"]})
continue
if name == "figure":
data = kwargs(
node.value,
module.id,
{"id", "path", "media_type", "caption", "alt"},
{"id", "path", "media_type", "caption", "alt"},
)
content.append(
{
"kind": "figure",
"localId": data["id"],
"assetId": _remember_figure(
planner, module, data, owner_id, node
),
"caption": data["caption"],
"alt": data["alt"],
}
)
continue
planner.error(
inv,
node,
"UNSUPPORTED_METHOD_CONTENT",
f"Unsupported method statement {type(node).__name__}",
)
def _call_formulas(
module, definition, node: ast.Assign, glyphs: dict[str, str]
) -> list[Json]:
keywords = {keyword.arg: keyword.value for keyword in node.value.keywords}
mapping = keywords.get("inputs")
if not isinstance(mapping, ast.Dict):
return []
formulas = []
for key, value in zip(mapping.keys, mapping.values):
if not isinstance(key, ast.Constant) or not isinstance(key.value, str):
continue
nodes = [
{
item_key: item_value
for item_key, item_value in item.items()
if item_key != "_ast"
}
for item in lower_expression(
module,
definition.function,
set(definition.parameters),
value,
given=False,
)
]
formulas.append(
{
"name": key.value,
"formulaText": _formula_text(nodes, glyphs),
"nodes": nodes,
}
)
return formulas
def _helper(
planner, inv, module, described: Json, owner_id: str, stack, cache, at: ast.AST
) -> Json:
loaded = planner.capture.load(
module.path.parent / described["path"], span(module.id, at)
)
function_name = described["function"]
key = (loaded.id, function_name)
cached = cache.get(key)
if cached is not None:
return cached
if key in stack:
planner.error(
inv, at, "UNSUPPORTED_METHOD_CONTENT", "Method dependencies must not cycle"
)
if function_name not in loaded.functions:
planner.error(
inv, at, "MISSING_FUNCTION", f"Missing calculation {function_name}"
)
_reject_deferred_content(planner, inv, loaded, function_name, at)
definition = planner.definitions.get(loaded.path, function_name)
plan = planner.ensure_plan(inv, loaded, function_name)
helper_id = identity("method", owner_id, f"{loaded.id}::{function_name}")
stack.add(key)
quantities = _quantities(planner, inv, loaded, definition, plan, at)
content, nested, helper_checks, helper_applicability = _method_content(
planner,
inv,
loaded,
definition,
plan,
quantities,
helper_id,
at,
stack,
cache,
)
record = {
"id": helper_id,
"moduleId": loaded.id,
"function": function_name,
"sourceHash": plan.source_hash,
"revision": _method_revision(plan.revision, content, nested),
"parameterNames": list(definition.parameters),
"outputNames": list(definition.outputs),
"quantities": quantities,
"metadata": _section_metadata(loaded, definition.function),
"content": content,
"helpers": nested,
}
if helper_checks:
record["checks"] = helper_checks
if helper_applicability:
record["applicability"] = helper_applicability
cache[key] = record
stack.remove(key)
return record
def _content_variables(content: list[Json]) -> set[str]:
found: set[str] = set()
for item in content:
if item["kind"] == "quantity":
found.add(item["variableName"])
elif item["kind"] == "section":
found.update(_content_variables(item["content"]))
return found
def _remember_figure(planner, module, data: Json, owner_id: str, node: ast.AST) -> str:
path = data["path"]
if Path(path).is_absolute() or "\\" in path or ":" in path or "\0" in path:
raise SourceError(
"INVALID_ASSET_PATH",
"Figure needs a module-relative local path",
location=span(module.id, node),
)
try:
requested = module.path.parent / path
asset_path = requested.resolve(strict=True)
asset_path.relative_to(planner.capture.root)
asset_bytes = asset_path.read_bytes()
except (OSError, ValueError, RuntimeError) as error:
raise SourceError(
"INVALID_ASSET_PATH",
f"Missing or escaping asset: {path}: {error}",
location=span(module.id, node),
) from error
if data["media_type"] not in {"image/png", "image/jpeg", "image/svg+xml"}:
raise SourceError(
"UNSUPPORTED_ASSET",
"Unsupported figure media type",
location=span(module.id, node),
)
asset_id = identity("figure", owner_id, data["id"])
planner.asset_files[requested.absolute()] = (asset_path, asset_bytes)
planner.assets[asset_id] = {
"id": asset_id,
"moduleId": module.id,
"path": path,
"mediaType": data["media_type"],
"sha256": hashlib.sha256(asset_bytes).hexdigest(),
}
return asset_id
def _declared_assignment(steps, variable: str) -> ast.AnnAssign | None:
for step in steps:
node = step.node
if (
isinstance(node, ast.AnnAssign)
and isinstance(node.target, ast.Name)
and node.target.id == variable
):
return node
found = _declared_assignment(step.child_steps or [], variable)
if found is not None:
return found
return None
def _place_table(planner, inv, call: ast.Call, section: Json, ids: set[str]) -> None:
found = _keywords(planner, inv, call)
_require(
planner,
inv,
found,
{
"id",
"method",
"title",
"cases",
"inputs",
"outputs",
"cases_axis",
"column_cap",
},
{"id", "method", "title", "cases"},
)
local_id = _text(planner, inv, found["id"])
title = _text(planner, inv, found["title"])
table_id = identity("table", inv.id, local_id)
if table_id in ids:
planner.error(
inv, call, "DUPLICATE_IDENTITY", "Duplicate method or table identity"
)
method = planner.method_index.get((inv.id, _text(planner, inv, found["method"])))
if method is None:
planner.error(
inv,
found["method"],
"UNKNOWN_METHOD",
"Table method must be an earlier declaration",
)
axis = "columns"
if "cases_axis" in found:
axis = _text(planner, inv, found["cases_axis"])
if axis not in {"columns", "rows"}:
planner.error(
inv,
found["cases_axis"],
"INVALID_METHOD",
"cases_axis must be columns or rows",
)
inputs = (
_names(planner, inv, found["inputs"], method["parameterNames"])
if "inputs" in found
else list(method["parameterNames"])
)
outputs = (
_names(planner, inv, found["outputs"], method["outputNames"])
if "outputs" in found
else list(method["outputNames"])
)
cases, cells = _cases(planner, inv, found["cases"].value, method, inputs, outputs)
record = {
"id": table_id,
"localId": local_id,
"invocationId": inv.id,
"title": title,
"methodId": method["id"],
"casesAxis": axis,
"inputs": inputs,
"outputs": outputs,
"cases": cases,
"cells": cells,
"location": span(inv.module.id, call),
}
if "column_cap" in found:
record["columnCap"] = _column_cap(planner, inv, found["column_cap"])
ids.add(table_id)
planner.tables.append(record)
section["items"].append(
{
"kind": "table",
"id": table_id,
"metadata": planner.metadata(inv, local_id, call),
}
)
def _column_cap(planner, inv, keyword: ast.keyword) -> int:
value = keyword.value
if (
not isinstance(value, ast.Constant)
or isinstance(value.value, bool)
or not isinstance(value.value, int)
or value.value < 1
):
planner.error(
inv, keyword, "INVALID_METHOD", "column_cap must be a positive integer"
)
return value.value
def _names(planner, inv, keyword: ast.keyword, known: list[str]) -> list[str]:
node = keyword.value
if not isinstance(node, ast.Tuple):
planner.error(
inv, keyword, "INVALID_METHOD", f"{keyword.arg} must be a literal tuple"
)
names: list[str] = []
for item in node.elts:
if (
not isinstance(item, ast.Constant)
or not isinstance(item.value, str)
or not item.value
):
planner.error(
inv,
item,
"UNKNOWN_QUANTITY",
"Quantity selections must be nonempty literal names",
)
if item.value in names:
planner.error(
inv, item, "DUPLICATE_QUANTITY", f"Duplicate quantity {item.value!r}"
)
if item.value not in known:
planner.error(
inv, item, "UNKNOWN_QUANTITY", f"Unknown quantity {item.value!r}"
)
names.append(item.value)
return names
def _cases(
planner, inv, node: ast.AST, method: Json, inputs: list[str], outputs: list[str]
) -> tuple[list[Json], list[Json]]:
if not isinstance(node, ast.Dict):
planner.error(
inv,
node,
"AMBIGUOUS_CASE_REFERENCE",
"Cases must be a literal heading mapping",
)
cases: list[Json] = []
cells: list[Json] = []
headings: set[str] = set()
for key, value in zip(node.keys, node.values):
if (
not isinstance(key, ast.Constant)
or not isinstance(key.value, str)
or not key.value
):
planner.error(
inv,
key or node,
"INVALID_METHOD",
"Case headings must be nonempty literal strings",
)
if key.value in headings:
planner.error(
inv,
key,
"DUPLICATE_CASE_HEADING",