-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_structure.py
More file actions
1505 lines (1310 loc) · 61.8 KB
/
Copy pathtest_structure.py
File metadata and controls
1505 lines (1310 loc) · 61.8 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
"""Verify the documentation architecture contract."""
from __future__ import annotations
from functools import cache
from pathlib import Path
import re
import subprocess
import sys
import pytest
import prik
ROOT = Path(__file__).parents[3]
DOCS_ROOT = ROOT / "docs"
FEATURE_MATRIX_PATH = DOCS_ROOT / "user/language-support/feature-matrix.md"
CLI_REFERENCE_PATH = DOCS_ROOT / "user/reference/cli-commands.md"
PYTHON_API_REFERENCE_PATH = DOCS_ROOT / "user/reference/python-api.md"
DOCUMENTATION_CHECKLIST_PATH = DOCS_ROOT / "maintainer/roadmap/documentation-content-checklist.md"
DOC_PATHS = sorted(path for path in DOCS_ROOT.rglob("*.md") if "old_docs" not in path.parts)
WEBSITE_DOCUMENTATION_PATHS = [
DOCS_ROOT / "index.md",
*sorted((DOCS_ROOT / "user").rglob("*.md")),
*sorted((DOCS_ROOT / "developer").rglob("*.md")),
*sorted((DOCS_ROOT / "maintainer").rglob("*.md")),
]
LEARNING_DOCUMENTATION_PATHS = [
*sorted((DOCS_ROOT / "user").rglob("*.md")),
*sorted((DOCS_ROOT / "developer").rglob("*.md")),
]
DEFERRED_C_PAGE_PATHS = [
ROOT / "docs/maintainer/design/cpython-integration.md",
ROOT / "docs/developer/c-parser-reference.md",
ROOT / "docs/user/examples/recipes/inspect-c-api.md",
]
MARKDOWN_LINK = re.compile(r"\[[^\]]+\]\(([^)#]+)(?:#[^)]+)?\)")
NEXT_NAVIGATION = re.compile(r"^\s*(?:#{2,6}\s+Next|\*\*Next\*\*:?)\s*$", re.IGNORECASE)
NEXT_SECTION_BOUNDARY = re.compile(r"^\s*(?:#{2,6}\s+|---\s*$|\*\*[^*]+\*\*)")
ALLOWED_CONTEXTUAL_FORWARD_LINK_SOURCE_PREFIXES = ("user/getting-started/", "user/guide/")
ALLOWED_CONTEXTUAL_FORWARD_LINK_PREFIXES = ("user/reference/pyi-contracts/",)
C_DOCS_START = "<!-- PRIK_C_DOCS_START"
C_DOCS_END = "PRIK_C_DOCS_END -->"
C_DOCS_DISABLED = "<!-- PRIK_C_DOCS_DISABLED:"
VISIBLE_C_DOCUMENTATION_EXCEPTIONS = {
"README.md": ("Fortran and C compilers",),
"docs/user/getting-started/index.md": ("`gcc`",),
"docs/user/getting-started/installation.md": (
"matching C\ncompiler",
"C compiler",
"brew install gcc@13",
"`gcc`",
"`gcc-13`",
"`clang`",
),
"docs/user/getting-started/verification.md": ("gcc --version", "clang --version"),
"docs/user/troubleshooting/compiler-issues.md": (
"C binding",
"C compiler",
"matching C\ncompiler",
"gcc --version",
"`clang`",
),
"docs/user/reference/cli-commands.md": ("C INCLUDE OPTIONS", "{fortran,c}"),
"docs/user/guide/enumerations.md": ("bind(C)",),
"docs/user/guide/wrapping-derived-types.md": ("bind(C)",),
"docs/user/guide/arrays.md": ("ORDER_C", "C-contiguous", "C-order", "C-oriented", 'order="C"'),
"docs/user/guide/raw-addresses.md": ("C-order", "C ordering"),
"docs/user/guide/building-shared-library.md": (
"PRIK_CFLAGS",
"C binding",
"C compiler",
"`gcc`",
"`clang`",
),
"docs/user/reference/semantic-pyi-format.md": (
"ORDER_C",
"C-contiguous",
"C-order",
"C-oriented",
"bind(C)",
"c_input",
),
}
VISIBLE_C_DOCUMENTATION = re.compile(
r"(?:"
r"(?<![A-Za-z0-9_])C(?:\+\+)?(?![A-Za-z0-9_])"
r"|CPython"
r"|Cython"
r"|C-input"
r"|bind\s*\(\s*c\s*\)"
r"|```c(?:\s|$)"
r"|\b(?:c_parser|c2ir|fortran_to_c|c_to_python|cpython_api|cpythoncode)\b"
r"|\b(?:ccode|cpreprocessor)\.py\b"
r"|\btest_c(?:2ir|_(?:semantic|parser|declarations|functions|structs|project|compiler|corpus|fixture|json|error|public))[A-Za-z0-9_]*\b"
r"|\b(?:bind_c|iso_c_binding)\b"
r"|\b[A-Za-z][A-Za-z0-9_]*_c\b"
r"|\bc_[A-Za-z0-9_]+\b"
r"|\b(?:ORDER_C|REQUIRE_C_CONTIGUOUS|NPY_C_CONTIGUOUS)\b"
r"|\b(?:CToIR|CFile|CProject|CParse|CDiagnostic)[A-Za-z0-9_]*\b"
r"|\b(?:parse_c|c_file|c_project|c_function|c_parameter|c_struct|c_type)_[A-Za-z0-9_]+\b"
r"|(?:tests/c/fixtures/native|tests/c/fixtures/parser|prik/parsers/c|/c/general/)"
r"|(?:c-parser|inspect-c-api|c-api)"
r"|\b(?:structs?|unions?|typedefs?|declarators?|bitfields?|K&R)\b"
r"|--language\s+c\b"
r"|(?:fortran\|c|\{fortran,c\}|\bc11\b|\bc17\b|\bc23\b)"
r"|\"language\"\s*:\s*\"c\""
r"|\.(?:c|h)(?:\b|`)"
r"|\b(?:CFLAGS|CC|gcc(?:-\d+)?|clang(?:-\d+)?|cJSON)\b"
r"|\bc-type(?:s|\b)"
r")"
)
REQUIRED_METADATA = {"title", "audience", "prerequisites", "related", "status", "publication"}
ALLOWED_PUBLICATION_STATES = {"draft", "reviewed"}
ALLOWED_STATUSES = {
"active-roadmap",
"design",
"draft",
"maintained",
"not-yet-implemented",
"planned-documentation",
}
TODO_STATUSES = {"draft", "not-yet-implemented", "planned-documentation"}
REQUIRED_AREA_INDEXES = [
"user/index.md",
"user/getting-started/index.md",
"user/guide/index.md",
"user/tutorials/index.md",
"user/examples/index.md",
"user/reference/index.md",
"user/language-support/index.md",
"user/faq/index.md",
"user/troubleshooting/index.md",
"developer/index.md",
"developer/contributing/index.md",
"maintainer/README.md",
"maintainer/design/index.md",
"maintainer/internal-architecture/index.md",
"maintainer/roadmap/index.md",
]
REQUIRED_REFERENCE_PAGES = [
"user/reference/index.md",
"user/reference/cli-commands.md",
"user/reference/python-api.md",
"user/reference/fortran-wrapper.md",
"user/reference/semantic-ir.md",
"user/reference/semantic-pyi-format.md",
"user/reference/pyi-contracts/index.md",
"user/reference/pyi-contracts/exports-and-modules.md",
"user/reference/pyi-contracts/functions-and-classes.md",
"user/reference/pyi-contracts/calls-and-results.md",
"user/reference/diagnostic-codes.md",
]
REQUIRED_ROADMAP_PAGES = [
"maintainer/roadmap/index.md",
"maintainer/roadmap/semantic-pyi-wrapper-checklist.md",
"maintainer/roadmap/documentation-content-checklist.md",
]
REQUIRED_GETTING_STARTED_PAGES = [
"user/getting-started/index.md",
"user/getting-started/installation.md",
"user/getting-started/verification.md",
"user/getting-started/first-wrapped-function.md",
"user/getting-started/first-wrapped-module.md",
"user/getting-started/beginner-workflow.md",
]
REQUIRED_USER_GUIDE_PAGES = [
"user/guide/index.md",
"user/guide/data-types.md",
"user/guide/arrays.md",
"user/guide/strings.md",
"user/guide/wrapping-functions.md",
"user/guide/wrapping-subroutines.md",
"user/guide/wrapping-modules.md",
"user/guide/optional-arguments.md",
"user/guide/generic-interfaces.md",
"user/guide/wrapping-derived-types.md",
"user/guide/allocatables.md",
"user/guide/pointers.md",
"user/guide/memory-management.md",
"user/guide/callbacks.md",
"user/guide/enumerations.md",
"user/guide/raw-addresses.md",
"user/guide/error-handling.md",
"user/guide/building-shared-library.md",
]
CLI_HELP_GROUP_HEADINGS = [
"commands:",
"positional arguments:",
"input selection:",
"input options:",
"generation modes:",
"compiler and preprocessing options:",
"preprocessing options:",
"C include options:",
"report options:",
"compiler options:",
"wrapper options:",
"native options:",
"probe options:",
"execution options:",
"output options:",
"diagnostic options:",
]
CLI_REFERENCE_OPTIONS = [
"paths",
"--help-build",
"--version",
"--language",
"--pyi",
"--sources",
"--preprocessor-adapter",
"--compiler",
"--preprocess-template",
"-I",
"--include-dir",
"-D",
"--define",
"-U",
"--undef",
"--std",
"--compiler-arg",
"--show-vars",
"--print-limit",
"--makefile",
"--strict-wrapper-names",
"--build-manifest",
"--native-fortran-sources",
"--native-compile-flags",
"--jobs",
"--native-objects",
"--native-library",
"--native-link-item",
"--native-library-dir",
"--format",
"--expr",
"--runner",
"--cache-dir",
"--refresh",
"--json",
"--out",
"--out-dir",
"--verbose",
"--no-color",
"--debug",
]
CLI_VISIBLE_HELP_OPTIONS = CLI_REFERENCE_OPTIONS
REQUIRED_SOURCE_NAVIGATION_PAGES = [
"developer/source-map.md",
"developer/feature-to-code-map.md",
"developer/repository-structure.md",
]
SOURCE_NAVIGATION_CORPUS = [
"docs/developer/source-map.md",
"docs/developer/feature-to-code-map.md",
"docs/developer/repository-structure.md",
"docs/maintainer/internal-architecture/pipeline-map.md",
"prik/README.md",
"prik/parsers/README.md",
"prik/parsers/c/README.md",
"prik/parsers/fortran/README.md",
"prik/parsers/pyi/README.md",
"prik/semantics/README.md",
"prik/compiling/README.md",
]
SOURCE_NAVIGATION_HOTSPOTS = [
"prik/__init__.py",
"prik/cli.py",
"prik/pipeline/build.py",
"prik/pipeline/preprocessing.py",
"prik/probes/c_types.py",
"prik/probes/fortran_types.py",
"prik/semantics/ownership.py",
"prik/parsers/c/parser.py",
"prik/parsers/c/cli.py",
"prik/parsers/fortran/parser.py",
"prik/parsers/fortran/cli.py",
"prik/parsers/pyi/parser.py",
"prik/semantics/models.py",
"prik/semantics/fortran2ir.py",
"prik/semantics/c2ir.py",
"prik/semantics/pyi2ir.py",
"prik/pipeline/pyi.py",
"prik/semantics/policy_completion.py",
"prik/wrapper_codegen/plan.py",
"prik/wrapper_codegen/planner.py",
"prik/wrapper_codegen/generator.py",
"prik/wrapper_codegen/c/binding.py",
"prik/wrapper_codegen/fortran/bridge.py",
"prik/wrapper_codegen/printers/pyi_printer.py",
"prik/wrapper_codegen/printers/source_printers.py",
"prik/compiling/objects.py",
"prik/compiling/compilers.py",
"prik/compiling/native_support.py",
"prik/naming/policy.py",
"prik/binding_support/",
]
SOURCE_NAVIGATION_PUBLIC_DOCS = [
"README.md",
"docs/user/examples/recipes/compiler-preprocessing.md",
"docs/user/examples/recipes/inspect-c-api.md",
"docs/user/examples/recipes/inspect-fortran-api.md",
"docs/user/examples/recipes/semantic-pyi-contracts.md",
"docs/user/reference/fortran-wrapper.md",
"docs/user/reference/pyi-contracts/index.md",
"docs/user/reference/cli-commands.md",
"docs/user/reference/diagnostic-codes.md",
"docs/user/reference/python-api.md",
"docs/user/reference/semantic-ir.md",
"docs/user/reference/semantic-pyi-format.md",
"docs/developer/build-system.md",
"docs/developer/c-parser-reference.md",
"docs/developer/fortran-parser-reference.md",
"docs/developer/quality-assurance.md",
"docs/user/language-support/feature-matrix.md",
]
SOURCE_NAVIGATION_TEST_TARGETS = [
"tests/c/fixtures/parser/",
"tests/fortran/command_line_interface/pipeline/",
"tests/fortran/source_parsing/parsing/",
"tests/fortran/source_parsing/parsing/test_fortran_fixture_suite.py",
"tests/fortran/source_parsing/parsing/test_public_entrypoints.py",
"tests/fortran/source_preprocessing/preprocessing/",
"tests/fortran/source_preprocessing/preprocessing/test_parser_boundaries.py",
"tests/fortran/semantic_pyi_format/",
"tests/fortran/semantic_pyi_format/parsing/",
"tests/fortran/semantic_pyi_format/semantics/",
"tests/fortran/semantic_pyi_format/pipeline/test_contract_package_generation.py",
"tests/fortran/semantic_pyi_format/pipeline/test_contract_loading.py",
"tests/fortran/semantic_pyi_format/end_to_end/test_authoritative_contract_runtime.py",
"tests/fortran/semantic_ir/semantics/",
"tests/c/semantics/conversion/",
"tests/fortran/semantic_pyi_format/pipeline/",
"tests/fortran/semantic_pyi_format/pipeline/test_modern_example.py",
"tests/shared/docs/test_examples.py",
"tests/shared/docs/test_structure.py",
"tests/fortran/",
"tests/fortran/pyi_contracts/exports_and_modules/",
"tests/fortran/building_shared_library/end_to_end/test_multi_source_builds.py",
"tests/fortran/building_shared_library/end_to_end/test_source_build_modes.py",
"tests/fortran/building_shared_library/end_to_end/test_runtime_compatibility.py",
]
PACKAGE_README_NAVIGATION_REFERENCES = [
"docs/developer/source-map.md",
"docs/developer/feature-to-code-map.md",
]
LEGACY_ACTIVE_DOC_REFERENCES = [
"docs/c_parser.md",
"docs/fortran_parser.md",
"docs/fortran_wrapper.md",
"docs/pyi_format.md",
"docs/pyi_wrapper_checklist.md",
"docs/quality.md",
"docs/semantics.md",
]
FEATURE_MATRIX_STATUSES = {
"Supported",
"Partially supported",
"Unsupported",
"Planned",
"Not implemented",
}
FEATURE_MATRIX_REQUIRED_FEATURES = [
"Fortran source wrapper builds",
"Scalar functions, subroutines, and baseline arrays",
"Generic procedure interfaces",
"Defined operators and assignment overloads",
"Output arguments and multiple results",
"Optional arguments",
"Allocatable array handles, descriptor arguments, and owned results",
"Pointer scalar projections and array handles",
"Array-valued function results",
"NumPy array argument contracts",
"Derived-type scalar boundaries and methods",
"Default and keyword constructors with finalizers",
"Module variables, constants, saved state, and common-block procedure state",
"Fortran enum constants",
"Scalar character arguments, results, and fields",
"Scalar kind coverage",
"Caller-ordered multi-source builds, Makefiles, verbose mode, and output placement",
"Visibility, naming, keyword escaping, and collision policy",
"Immediate call-scoped Python callbacks",
"Runtime error projection, GIL policy, recursion, OpenMP path, and GNU ABI checks",
"Fortran parse, semantic IR, and `.pyi` inspection",
"Semantic `.pyi` wrapper builds from explicit native artifacts",
"Assumed-size, assumed-rank, and lower-bound array contracts",
"Scalar inheritance and polymorphic dispatch",
"Unproved pointer lifetime and ownership-changing operations",
"Persistent callbacks and procedure pointers",
"Advanced multi-source dependency discovery and external-library integration",
"Blocked array forms",
"Unsupported polymorphic forms",
"Generic constructor interfaces and overloaded runtime initialization",
"Character arrays and mutable deferred-length character storage",
"Wider-than-supported real, complex, and logical storage",
"Full semantic `.pyi` parity across all wrapper scenarios",
"MPI examples and distribution constraints",
"Generated reference pages for modules, functions, and classes",
]
REQUIRED_EXAMPLE_RECIPE_PAGES = [
"user/examples/recipes/build-and-import-python-api.md",
"user/examples/recipes/inspect-fortran-api.md",
"user/examples/recipes/inspect-c-api.md",
"user/examples/recipes/semantic-pyi-contracts.md",
"user/examples/recipes/control-cli-output.md",
"user/examples/recipes/use-python-inspection-apis.md",
"user/examples/recipes/compiler-preprocessing.md",
]
EXAMPLE_DOCUMENTATION_PAGES = [
path.relative_to(DOCS_ROOT).as_posix()
for path in sorted((DOCS_ROOT / "user/examples").rglob("*.md"))
if path.name != "index.md"
]
MAJOR_SOURCE_PACKAGES = [
"prik/parsers/",
"prik/semantics/",
"prik/wrapper_codegen/",
"prik/compiling/",
]
PACKAGE_READMES = [
"prik/README.md",
"prik/parsers/README.md",
"prik/semantics/README.md",
"prik/compiling/README.md",
]
ARCHIVED_OLD_DOCS = [
"old_docs/tutorial.md",
"old_docs/examples.md",
"old_docs/fortran_wrapper.md",
"old_docs/semantics.md",
"old_docs/pyi_format.md",
"old_docs/diagnostic_codes.md",
"old_docs/pyi_wrapper_checklist.md",
"old_docs/developper_guide.md",
"old_docs/quality.md",
"old_docs/c_parser.md",
"old_docs/fortran_parser.md",
"old_docs/wrapper_design_notes.md",
"old_docs/architecture/semantic_multilanguage_wrapper_runtime_architecture.md",
]
OLD_TOP_LEVEL_DOCS = [
"tutorial.md",
"examples.md",
"fortran_wrapper.md",
"semantics.md",
"pyi_format.md",
"diagnostic_codes.md",
"pyi_wrapper_checklist.md",
"developper_guide.md",
"quality.md",
"c_parser.md",
"fortran_parser.md",
"wrapper_design_notes.md",
]
def _front_matter(path: Path) -> tuple[dict[str, str], str]:
lines = path.read_text(encoding="utf-8").splitlines()
assert lines and lines[0] == "---", f"{path.relative_to(ROOT)}: missing front matter"
try:
end = lines.index("---", 1)
except ValueError as error:
raise AssertionError(f"{path.relative_to(ROOT)}: unclosed front matter") from error
metadata: dict[str, str] = {}
for line in lines[1:end]:
if not line.strip():
continue
key, separator, value = line.partition(":")
assert separator, f"{path.relative_to(ROOT)}: invalid front matter line: {line!r}"
metadata[key.strip()] = value.strip()
return metadata, "\n".join(lines[end + 1 :])
def _visible_documentation_source(path: Path) -> str:
lines = path.read_text(encoding="utf-8").splitlines()
if path != ROOT / "README.md" and lines and lines[0] == "---":
lines = lines[lines.index("---", 1) + 1 :]
visible: list[str] = []
hidden: str | None = None
for line in lines:
stripped = line.strip()
if stripped == C_DOCS_START:
assert not hidden, f"{path.relative_to(ROOT)}: nested deferred documentation comment"
hidden = "deferred-c"
elif stripped == "<!--":
assert not hidden, f"{path.relative_to(ROOT)}: nested documentation comment"
hidden = "ordinary"
elif stripped == C_DOCS_END:
assert hidden == "deferred-c", f"{path.relative_to(ROOT)}: unmatched deferred documentation comment end"
hidden = None
elif stripped == "-->" and hidden == "ordinary":
hidden = None
elif hidden == "deferred-c":
assert "--" not in line, f"{path.relative_to(ROOT)}: invalid double hyphen in deferred comment"
elif hidden == "ordinary":
continue
elif not line.lstrip().startswith(C_DOCS_DISABLED):
visible.append(line)
assert not hidden, f"{path.relative_to(ROOT)}: unclosed deferred documentation comment"
return "\n".join(visible)
def _instructional_body_without_next(body: str) -> str:
instructional_lines: list[str] = []
inside_next = False
for line in body.splitlines():
if NEXT_NAVIGATION.match(line):
inside_next = True
continue
if inside_next and NEXT_SECTION_BOUNDARY.match(line):
inside_next = False
if not inside_next:
instructional_lines.append(line)
return "\n".join(instructional_lines)
def _next_navigation_items(body: str) -> list[tuple[int, str, bool]]:
items: list[tuple[int, str, bool]] = []
current_line: int | None = None
current_parts: list[str] = []
inside_next = False
def flush_current() -> None:
nonlocal current_line, current_parts
if current_line is not None:
items.append((current_line, " ".join(current_parts), True))
current_line = None
current_parts = []
for line_number, line in enumerate(body.splitlines(), start=1):
if NEXT_NAVIGATION.match(line):
flush_current()
inside_next = True
continue
if inside_next and NEXT_SECTION_BOUNDARY.match(line):
flush_current()
inside_next = False
continue
if not inside_next or not line.strip():
continue
if line.startswith("- "):
flush_current()
current_line = line_number
current_parts = [line[2:].strip()]
elif current_line is not None and line.startswith(" "):
current_parts.append(line.strip())
else:
flush_current()
items.append((line_number, line.strip(), False))
flush_current()
return items
def _combined_text(relative_paths: list[str]) -> str:
return "\n".join((ROOT / relative_path).read_text(encoding="utf-8") for relative_path in relative_paths)
@cache
def _site_navigation_positions() -> dict[str, int]:
navigation_entry = re.compile(r": ([^#\s]+\.md)\s*$")
paths: list[str] = []
for line in (ROOT / "mkdocs.yml").read_text(encoding="utf-8").splitlines():
if line.lstrip().startswith("#"):
continue
match = navigation_entry.search(line)
if match:
paths.append(match.group(1))
return {path: index for index, path in enumerate(paths)}
def _user_guide_index_order() -> list[str]:
_, body = _front_matter(DOCS_ROOT / "user/guide/index.md")
guide_root = (DOCS_ROOT / "user/guide").resolve()
paths: list[str] = []
for target in MARKDOWN_LINK.findall(body):
resolved = (guide_root / target).resolve()
if resolved.parent != guide_root or resolved.name == "index.md":
continue
relative_path = resolved.relative_to(DOCS_ROOT).as_posix()
if relative_path not in paths:
paths.append(relative_path)
return paths
@cache
def _prik_cli_help() -> str:
commands = [
["--help"],
["input.f90", "--help"],
["parse", "--help"],
["semantics", "--help"],
["generate", "--help"],
["probe", "--help"],
]
outputs = []
for command in commands:
result = subprocess.run(
[sys.executable, "-m", "prik", *command],
cwd=ROOT,
capture_output=True,
text=True,
check=True,
)
outputs.append(result.stdout)
return "\n".join(outputs)
def _feature_matrix_rows() -> list[dict[str, str]]:
header = "| Feature | Status | User docs | Source owner | Evidence | Limitations |"
columns = ["Feature", "Status", "User docs", "Source owner", "Evidence", "Limitations"]
rows: list[dict[str, str]] = []
in_table = False
for line in FEATURE_MATRIX_PATH.read_text(encoding="utf-8").splitlines():
if line == header:
in_table = True
continue
if not in_table:
continue
if line.startswith("| ---"):
continue
if not line.startswith("|"):
in_table = False
continue
cells = [cell.strip() for cell in line.strip().strip("|").split("|")]
assert len(cells) == len(columns), f"invalid feature matrix row: {line!r}"
rows.append(dict(zip(columns, cells, strict=True)))
return rows
FEATURE_MATRIX_ROWS = _feature_matrix_rows()
@pytest.mark.parametrize("path", DOC_PATHS, ids=lambda path: str(path.relative_to(ROOT)))
def test_documentation_page_metadata(path: Path) -> None:
metadata, body = _front_matter(path)
missing = REQUIRED_METADATA - metadata.keys()
assert not missing, f"{path.relative_to(ROOT)}: missing metadata fields: {sorted(missing)}"
for key in REQUIRED_METADATA:
assert metadata[key], f"{path.relative_to(ROOT)}: metadata field {key!r} is empty"
assert metadata["status"] in ALLOWED_STATUSES, f"{path.relative_to(ROOT)}: unknown status {metadata['status']!r}"
assert metadata["publication"] in ALLOWED_PUBLICATION_STATES, (
f"{path.relative_to(ROOT)}: unknown publication state {metadata['publication']!r}"
)
if metadata["status"] in TODO_STATUSES:
assert "## TODO" in body, f"{path.relative_to(ROOT)}: unfinished pages must include a TODO section"
assert "TODO:" in body, f"{path.relative_to(ROOT)}: TODO section must contain explicit TODO markers"
@pytest.mark.parametrize(
"path",
[
ROOT / "README.md",
*(path for path in WEBSITE_DOCUMENTATION_PATHS if _front_matter(path)[0].get("publication") == "reviewed"),
],
ids=lambda path: str(path.relative_to(ROOT)),
)
def test_deferred_c_documentation_is_not_visible(path: Path) -> None:
visible = _visible_documentation_source(path)
for allowed_text in VISIBLE_C_DOCUMENTATION_EXCEPTIONS.get(str(path.relative_to(ROOT)), ()):
visible = visible.replace(allowed_text, "")
match = VISIBLE_C_DOCUMENTATION.search(visible)
assert match is None, f"{path.relative_to(ROOT)}: visible deferred documentation: {match.group(0)!r}"
@pytest.mark.parametrize("path", DEFERRED_C_PAGE_PATHS, ids=lambda path: str(path.relative_to(ROOT)))
def test_dedicated_deferred_c_pages_have_no_visible_body(path: Path) -> None:
assert _visible_documentation_source(path).strip() == ""
def test_deferred_c_pages_are_not_in_site_navigation() -> None:
lines = (ROOT / "mkdocs.yml").read_text(encoding="utf-8").splitlines()
active_navigation = "\n".join(line for line in lines if not line.lstrip().startswith("#"))
assert "Inspect a C API" not in active_navigation
assert "C Parser Reference" not in active_navigation
assert any("PRIK_C_DOCS" in line and "inspect-c-api.md" in line for line in lines)
assert any("PRIK_C_DOCS" in line and "c-parser-reference.md" in line for line in lines)
def test_readme_follows_one_points_workflow_from_build_through_contract_rebuild() -> None:
readme = _visible_documentation_source(ROOT / "README.md")
quick_start = readme.split("## Installation & Quick Start", maxsplit=1)[1].split(
"## How it works",
maxsplit=1,
)[0]
installation_index = quick_start.index("python3 -m pip install prik")
version_index = quick_start.index("prik --version", installation_index)
help_index = quick_start.index("python3 -m prik --help")
source_build_command_index = quick_start.index(
"python3 -m prik points.f90 --out geometry",
help_index,
)
source_build_tree_index = quick_start.index(
".\n points.f90\n geometry.so\n __prik__/",
source_build_command_index,
)
explicit_source_build_command_index = quick_start.index(
"python3 -m prik points.f90 \\\n --out geometry \\\n --out-dir build/geometry",
source_build_tree_index,
)
explicit_source_build_tree_index = quick_start.index(
"build/geometry/\n geometry.<extension-suffix>.so",
explicit_source_build_command_index,
)
pyi_generation_command_index = quick_start.index(
"python3 -m prik generate --pyi points.f90 --out contracts",
explicit_source_build_tree_index,
)
pyi_contract_tree_index = quick_start.index(
"contracts/\n __init__.pyi\n points.pyi",
pyi_generation_command_index,
)
pyi_contract_body_index = quick_start.index(
"class point:\n"
" def __init__(\n"
" self,\n"
" *,\n"
" x: Float64 = 0.0,\n"
" y: Float64 = 0.0",
pyi_contract_tree_index,
)
move_contract_index = quick_start.index(
"@native_call([Arg(0), Addr(Arg(1)), Addr(Arg(2))])\ndef move(",
pyi_contract_body_index,
)
norm_contract_index = quick_start.index("def norm_squared(", move_contract_index)
pyi_build_command_index = quick_start.index(
"python3 -m prik contracts/__init__.pyi",
norm_contract_index,
)
native_source_argument_index = quick_start.index("--native-fortran-sources points.f90", pyi_build_command_index)
output_name_index = quick_start.index("--out geometry", native_source_argument_index)
pyi_build_tree_index = quick_start.index("build/geometry_from_pyi/", output_name_index)
import_index = quick_start.index("import geometry.points as points", pyi_build_tree_index)
constructor_index = quick_start.index("item = points.point(", import_index)
mutation_index = quick_start.index("points.move(item", constructor_index)
runtime_output_index = quick_start.index("# 20.0", mutation_index)
verbose_command_index = quick_start.index(
"python3 -m prik points.f90 \\\n --out geometry_debug",
runtime_output_index,
)
verbose_fortran_flag_index = quick_start.index("--wrapper-fortran-flags=-O2", verbose_command_index)
verbose_c_flag_index = quick_start.index("--wrapper-c-flags=-O2", verbose_fortran_flag_index)
verbose_output_index = quick_start.index("generated Python binding", verbose_c_flag_index)
assert installation_index < version_index < help_index < source_build_command_index
assert source_build_command_index < source_build_tree_index < explicit_source_build_command_index
assert explicit_source_build_command_index < explicit_source_build_tree_index < pyi_generation_command_index
assert pyi_generation_command_index < pyi_contract_tree_index < pyi_contract_body_index
assert pyi_contract_body_index < move_contract_index < norm_contract_index < pyi_build_command_index
assert pyi_build_command_index < native_source_argument_index < output_name_index < pyi_build_tree_index
assert pyi_build_tree_index < import_index < constructor_index < mutation_index < runtime_output_index
assert runtime_output_index < verbose_command_index
assert verbose_command_index < verbose_fortran_flag_index < verbose_c_flag_index < verbose_output_index
assert "--parse" not in readme
assert "--semantics" not in readme
assert "scale.f90" not in readme
assert "SCALE" not in readme
assert "python3 -m prik solver.f90" not in quick_start
assert "fruntime_abi_f90" not in readme
assert "solver.f90" not in readme
assert "add1" not in readme
assert "distance2" not in readme
assert "point_api" not in readme
assert "build/points" not in readme
assert "tests/data/fortran/general/basic_subroutine.f90" not in readme
assert "contracts/basic_subroutine/basic_subroutine.pyi" not in readme
def test_installation_separates_pypi_users_from_editable_contributors() -> None:
installation = _visible_documentation_source(DOCS_ROOT / "user/getting-started/installation.md")
user_section = installation.split("## User Installation", maxsplit=1)[1].split(
"## Contributor Installation",
maxsplit=1,
)[0]
contributor_section = installation.split("## Contributor Installation", maxsplit=1)[1].split(
"## Platform Support",
maxsplit=1,
)[0]
assert "python3 -m pip install prik" in user_section
assert "pip install -e" not in user_section
assert "git clone https://github.com/PyNumLab/prik.git" in contributor_section
assert 'python3 -m pip install -e ".[qa]"' in contributor_section
@pytest.mark.parametrize("relative_path", REQUIRED_AREA_INDEXES)
def test_required_documentation_area_exists(relative_path: str) -> None:
assert (DOCS_ROOT / relative_path).is_file()
def test_documentation_root_uses_three_audience_lanes() -> None:
directories = {path.name for path in DOCS_ROOT.iterdir() if path.is_dir()}
root_pages = {path.name for path in DOCS_ROOT.glob("*.md")}
assert directories == {
"user",
"developer",
"maintainer",
"javascripts",
"stylesheets",
"old_docs",
}
assert root_pages == {"index.md"}
@pytest.mark.parametrize(
("lane", "audience_terms"),
[
("user", ("users",)),
("developer", ("developers", "contributors")),
("maintainer", ("maintainers",)),
],
)
def test_documentation_lane_has_consistent_audience(lane: str, audience_terms: tuple[str, ...]) -> None:
for path in (DOCS_ROOT / lane).rglob("*.md"):
metadata, _ = _front_matter(path)
assert any(term in metadata["audience"] for term in audience_terms)
if lane != "maintainer":
assert "maintainers" not in metadata["audience"]
else:
assert metadata["audience"] == "maintainers"
@pytest.mark.parametrize("path", LEARNING_DOCUMENTATION_PATHS, ids=lambda path: str(path.relative_to(ROOT)))
def test_website_documentation_does_not_link_to_maintainer_lane(path: Path) -> None:
maintainer_root = (DOCS_ROOT / "maintainer").resolve()
for target in MARKDOWN_LINK.findall(_visible_documentation_source(path)):
if target.startswith(("http://", "https://", "mailto:")):
continue
resolved = (path.parent / target).resolve()
assert not resolved.is_relative_to(maintainer_root), (
f"{path.relative_to(ROOT)}: website link enters maintainer lane: {target}"
)
def test_readme_documentation_links_follow_site_navigation_order() -> None:
readme = _visible_documentation_source(ROOT / "README.md")
documentation = readme.split("## Documentation", maxsplit=1)[1].split(
"## Development",
maxsplit=1,
)[0]
positions = _site_navigation_positions()
linked_positions = [
positions[target.removeprefix("docs/")]
for target in MARKDOWN_LINK.findall(documentation)
if target.startswith("docs/")
]
assert linked_positions == sorted(linked_positions)
@pytest.mark.parametrize("relative_path", REQUIRED_REFERENCE_PAGES)
def test_required_reference_page_exists(relative_path: str) -> None:
assert (DOCS_ROOT / relative_path).is_file()
@pytest.mark.parametrize("relative_path", REQUIRED_REFERENCE_PAGES)
def test_reference_page_is_in_site_navigation(relative_path: str) -> None:
site_configuration = (ROOT / "mkdocs.yml").read_text(encoding="utf-8")
assert relative_path in site_configuration
@pytest.mark.parametrize("relative_path", REQUIRED_ROADMAP_PAGES)
def test_required_roadmap_page_exists(relative_path: str) -> None:
assert (DOCS_ROOT / relative_path).is_file()
def test_site_navigation_includes_all_publishable_lanes_and_excludes_archive() -> None:
site_configuration = (ROOT / "mkdocs.yml").read_text(encoding="utf-8")
assert "old_docs/**" in site_configuration
positions = _site_navigation_positions()
assert "user/index.md" in positions
assert "developer/index.md" in positions
assert "maintainer/README.md" in positions
def test_user_guide_navigation_follows_index_reading_order() -> None:
positions = _site_navigation_positions()
navigation_order = [
path
for path, _ in sorted(positions.items(), key=lambda item: item[1])
if path.startswith("user/guide/") and path != "user/guide/index.md"
]
assert navigation_order == _user_guide_index_order()
@pytest.mark.parametrize("relative_path", REQUIRED_GETTING_STARTED_PAGES)
def test_required_getting_started_page_is_maintained_and_navigable(relative_path: str) -> None:
path = DOCS_ROOT / relative_path
assert path.is_file()
metadata, body = _front_matter(path)
assert metadata["status"] == "maintained"
assert relative_path in (ROOT / "mkdocs.yml").read_text(encoding="utf-8")
for target in MARKDOWN_LINK.findall(body):
if target.startswith(("http://", "https://")):
continue
assert (path.parent / target).resolve().exists(), f"{relative_path}: missing link target {target}"
@pytest.mark.parametrize("relative_path", REQUIRED_GETTING_STARTED_PAGES)
def test_getting_started_page_is_completed_in_documentation_checklist(relative_path: str) -> None:
checklist = DOCUMENTATION_CHECKLIST_PATH.read_text(encoding="utf-8")
assert f"- [x] `docs/{relative_path}`" in checklist
@pytest.mark.parametrize("relative_path", REQUIRED_USER_GUIDE_PAGES)
def test_required_user_guide_page_is_maintained_and_navigable(relative_path: str) -> None:
path = DOCS_ROOT / relative_path
assert path.is_file()
metadata, body = _front_matter(path)
assert metadata["status"] == "maintained"
assert relative_path in (ROOT / "mkdocs.yml").read_text(encoding="utf-8")
for target in MARKDOWN_LINK.findall(body):
if target.startswith(("http://", "https://")):
continue
assert (path.parent / target).resolve().exists(), f"{relative_path}: missing link target {target}"
@pytest.mark.parametrize("relative_path", REQUIRED_USER_GUIDE_PAGES)
def test_user_guide_page_is_completed_in_documentation_checklist(relative_path: str) -> None:
checklist = DOCUMENTATION_CHECKLIST_PATH.read_text(encoding="utf-8")
assert f"- [x] `docs/{relative_path}`" in checklist
@pytest.mark.parametrize(
"relative_path",
[*REQUIRED_GETTING_STARTED_PAGES[1:], *REQUIRED_USER_GUIDE_PAGES[1:], *EXAMPLE_DOCUMENTATION_PAGES],
)
def test_sequential_user_pages_do_not_link_forward_from_instructional_prose(relative_path: str) -> None:
path = DOCS_ROOT / relative_path
_, body = _front_matter(path)
body = _instructional_body_without_next(body)
positions = _site_navigation_positions()
if relative_path not in positions:
pytest.skip(f"{relative_path}: not active in site navigation")
source_position = positions[relative_path]
for target in MARKDOWN_LINK.findall(body):
target_path = (path.parent / target).resolve()
if not target_path.is_relative_to(DOCS_ROOT):
continue
target_relative = target_path.relative_to(DOCS_ROOT).as_posix()
if target_relative not in positions:
continue
if relative_path.startswith(ALLOWED_CONTEXTUAL_FORWARD_LINK_SOURCE_PREFIXES) and target_relative.startswith(
ALLOWED_CONTEXTUAL_FORWARD_LINK_PREFIXES
):
continue
assert positions[target_relative] <= source_position, f"{relative_path}: forward link to {target_relative}"
@pytest.mark.parametrize(
"relative_path",
[*REQUIRED_GETTING_STARTED_PAGES[1:], *REQUIRED_USER_GUIDE_PAGES[1:]],
)
def test_next_sections_use_linked_bullet_destinations(relative_path: str) -> None:
_, body = _front_matter(DOCS_ROOT / relative_path)
for line_number, item, is_bullet in _next_navigation_items(body):
assert is_bullet, f"{relative_path}:{line_number}: Next content must be a bullet item"
assert MARKDOWN_LINK.search(item), f"{relative_path}:{line_number}: Next item must include a Markdown link"
@pytest.mark.parametrize("relative_path", REQUIRED_USER_GUIDE_PAGES)
def test_user_guide_commands_do_not_expose_fixture_paths(relative_path: str) -> None:
page = (DOCS_ROOT / relative_path).read_text(encoding="utf-8")
assert "python3 -m prik tests/" not in page
@pytest.mark.parametrize(
"relative_path",
[
"index.md",
"user/index.md",
*REQUIRED_GETTING_STARTED_PAGES,
*REQUIRED_USER_GUIDE_PAGES,
],
)
def test_reviewed_user_pages_do_not_expose_internal_evidence(relative_path: str) -> None:
page = _visible_documentation_source(DOCS_ROOT / relative_path)
assert "## Evidence" not in page
assert "## Runtime Evidence" not in page
assert "Runtime tests:" not in page
assert "../../../tests/" not in page
assert "../../tests/" not in page
assert "../tests/" not in page
@pytest.mark.parametrize(
"relative_path",
[