-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstandard_builder.py
More file actions
1121 lines (912 loc) · 43 KB
/
Copy pathstandard_builder.py
File metadata and controls
1121 lines (912 loc) · 43 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
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <https://unlicense.org>
"""
standard_builder.py
Builds a complete C++ standard document from std.tex by:
1. Parsing std.tex to extract chapter order
2. Converting each chapter in order
3. Concatenating with merged cross-reference link definitions
"""
import os
import re
import subprocess
import sys
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from pylatexenc.latexwalker import LatexMacroNode, LatexWalker
from .utils import cleanup_temp_files, create_temp_tex_file, ensure_dir, expand_latex_inputs
def _convert_chapter_worker(
work_unit: dict,
draft_dir: Path,
output_dir: Path,
label_index_file: Path,
verbose: bool = False,
) -> dict:
"""
Worker function for parallel chapter conversion.
Must be at module level to be picklable for multiprocessing.
Args:
work_unit: Dictionary describing the work to do:
- type: 'single' or 'collision'
- stable_name: Output file stem
- chapter: Chapter name (for single)
- chapters: List of chapter names (for collision/merge)
draft_dir: Path to cplusplus/draft source directory
output_dir: Path to output directory
label_index_file: Path to label index Lua file
verbose: Print progress (usually False for parallel workers)
Returns:
Dictionary with conversion results:
- success: bool
- output_file: Path to output file (if successful)
- stable_name: str
- error: str (if failed)
"""
from .converter import Converter
draft_dir = Path(draft_dir)
output_dir = Path(output_dir)
stable_name = work_unit["stable_name"]
try:
# Create converter instance for this worker
converter = Converter()
# Determine input file(s)
temp_files = []
if work_unit["type"] == "collision":
# Merge multiple files
chapters = work_unit["chapters"]
chapter_files = []
for ch in chapters:
ch_file = draft_dir / f"{ch}.tex"
if ch_file.exists():
chapter_files.append(ch_file)
# Merge files into temporary file
merged_content = []
for tex_file in chapter_files:
content = tex_file.read_text(encoding="utf-8")
merged_content.append(content)
# Create temporary merged file
file_to_convert = create_temp_tex_file("\n\n".join(merged_content))
temp_files.append(file_to_convert)
else:
# Single file conversion
chapter = work_unit["chapter"]
chapter_file = draft_dir / f"{chapter}.tex"
if not chapter_file.exists():
return {
"success": False,
"stable_name": stable_name,
"error": f"{chapter}.tex not found",
}
file_to_convert = chapter_file
# Expand \input{} commands for front/back
if chapter in ["front", "back"]:
content = chapter_file.read_text(encoding="utf-8")
base_dir = chapter_file.parent
expanded = expand_latex_inputs(content, base_dir)
file_to_convert = create_temp_tex_file(expanded)
temp_files.append(file_to_convert)
# Convert to markdown
output_file = output_dir / f"{stable_name}.md"
converter.convert_file(
file_to_convert,
output_file=output_file,
standalone=True,
verbose=False,
current_file_stem=stable_name,
label_index_file=label_index_file,
source_dir=draft_dir,
)
# Cleanup temporary files
cleanup_temp_files(temp_files)
return {"success": True, "output_file": output_file, "stable_name": stable_name}
except Exception as e:
# Cleanup temporary files on error
cleanup_temp_files(temp_files)
return {"success": False, "stable_name": stable_name, "error": str(e)}
class StandardBuilder:
"""Builds complete standard document from std.tex driver file"""
def __init__(self, draft_dir: Path):
"""
Args:
draft_dir: Path to cplusplus/draft source directory
"""
self.draft_dir = Path(draft_dir)
self.std_tex = self.draft_dir / "std.tex"
def convert_diagrams_to_svg(self, output_dir: Path, verbose: bool = False) -> list[Path]:
"""
Convert Graphviz .dot files to SVG format for embedding in markdown.
The C++ standard uses importgraphic environments that reference PDF files
generated from .dot files. This method converts those .dot files directly
to SVG format which can be embedded in GitHub Flavored Markdown.
Args:
output_dir: Directory where images/ subdirectory will be created
verbose: Print progress messages
Returns:
List of generated SVG file paths
"""
# Find all .dot files in the draft source directory
dot_files = list(self.draft_dir.glob("*.dot"))
if not dot_files:
if verbose:
print("No .dot diagram files found")
return []
# Create images subdirectory
images_dir = output_dir / "images"
ensure_dir(images_dir)
if verbose:
print(f"Converting {len(dot_files)} diagrams to SVG...")
svg_files = []
for dot_file in dot_files:
svg_file = images_dir / (dot_file.stem + ".svg")
try:
# Use Graphviz dot command to convert to SVG
subprocess.run(
["dot", "-Tsvg", str(dot_file), "-o", str(svg_file)],
capture_output=True,
text=True,
check=True,
)
svg_files.append(svg_file)
if verbose:
print(f" {dot_file.name} → {svg_file.name}")
except subprocess.CalledProcessError as e:
print(
f"Warning: Failed to convert {dot_file.name}: {e.stderr}",
file=sys.stderr,
)
except FileNotFoundError:
print(
"Error: Graphviz (dot) not found. Install with: apt install graphviz",
file=sys.stderr,
)
break
if verbose and svg_files:
print(f"Generated {len(svg_files)} SVG diagrams in {images_dir}")
return svg_files
def extract_chapter_order(
self, include_frontmatter: bool = True, include_backmatter: bool = True
) -> list[str]:
r"""
Parse std.tex to extract ordered list of chapter filenames.
Uses pylatexenc to parse LaTeX and extract \include{filename} commands.
Args:
include_frontmatter: Include frontmatter chapters (cover, TOC)
include_backmatter: Include backmatter chapters (index)
Returns:
List of chapter filenames (without .tex extension)
"""
if not self.std_tex.exists():
raise FileNotFoundError(f"std.tex not found at {self.std_tex}")
content = self.std_tex.read_text(encoding="utf-8")
# Use pylatexenc to parse the LaTeX
walker = LatexWalker(content)
nodelist, _, _ = walker.get_latex_nodes()
chapters = []
in_frontmatter = False
in_mainmatter = False
in_backmatter = False
# Walk through nodes looking for \include{} commands
def visit_node(node):
nonlocal in_frontmatter, in_mainmatter, in_backmatter
if isinstance(node, LatexMacroNode):
# Track document sections
if node.macroname == "frontmatter":
in_frontmatter = True
elif node.macroname == "mainmatter":
in_frontmatter = False
in_mainmatter = True
elif node.macroname == "backmatter":
in_mainmatter = False
in_backmatter = True
elif node.macroname == "include":
# Decide whether to include based on section
should_include = False
if (
(in_frontmatter and include_frontmatter)
or in_mainmatter
or (in_backmatter and include_backmatter)
):
should_include = True
if should_include and node.nodeargd and node.nodeargd.argnlist:
# Extract the filename from the argument
arg = node.nodeargd.argnlist[0]
if arg and hasattr(arg, "nodelist"):
# Get the text content
filename = "".join(
n.chars if hasattr(n, "chars") else "" for n in arg.nodelist
)
if filename:
chapters.append(filename.strip())
# Recursively visit child nodes
if hasattr(node, "nodelist") and node.nodelist:
for child in node.nodelist:
visit_node(child)
for node in nodelist:
visit_node(node)
return chapters
def _expand_input_commands(self, tex_file: Path) -> Path:
"""
Expand \\input{} commands in a LaTeX file by inlining referenced files.
Creates a temporary file with all \\input{filename} commands replaced
by the content of filename.tex.
Args:
tex_file: Path to LaTeX file that may contain \\input{} commands
Returns:
Path to temporary file with expanded content
"""
content = tex_file.read_text(encoding="utf-8")
base_dir = tex_file.parent
expanded = expand_latex_inputs(content, base_dir)
# Create temporary file with expanded content
return create_temp_tex_file(expanded)
def extract_stable_name_from_tex(self, tex_file: Path, converter) -> str:
"""
Extract stable section name from a .tex file using Pandoc.
Uses the existing Pandoc + cpp-sections.lua pipeline to parse the LaTeX
and extract the first section's stable name (the label in \rSec0[label]{Title}).
Args:
tex_file: Path to .tex file
converter: Converter instance to use for parsing
Returns:
Stable name prefix (e.g., "expr" for expressions.tex)
Falls back to filename stem if extraction fails
Examples:
expressions.tex → "expr" (from \rSec0[expr]{Expressions})
statements.tex → "stmt" (from \rSec0[stmt.stmt]{Statements})
preprocessor.tex → "cpp" (from \rSec0[cpp]{Preprocessing directives})
"""
try:
# Find the first \rSec0[label] line in the file
# This is the top-level section that defines the stable name
rsec0_line = None
with tex_file.open("r", encoding="utf-8") as f:
for line in f:
# Look for \rSec0[label]{Title} pattern
if r"\rSec0[" in line:
rsec0_line = line.strip()
break
if not rsec0_line:
# No \rSec0 found, fall back to filename
return tex_file.stem
# Create temporary file with just the \rSec0 line
# This avoids issues with unclosed LaTeX environments when truncating
tmp_path = create_temp_tex_file(rsec0_line + "\n")
try:
# Convert with Pandoc (cpp-sections.lua extracts the label)
markdown = converter.convert_file(
tmp_path, output_file=None, standalone=False, verbose=False
)
# Extract first <a id="..."> anchor created by cpp-sections.lua
# Format: <a id="stable.name">[stable.name]</a>
match = re.search(r'<a id="([^"]+)">', markdown)
if match:
label = match.group(1)
# Extract prefix before first dot
# "expr.prim" → "expr"
# "stmt.stmt" → "stmt"
# "intro.scope" → "intro"
stable_name = label.split(".")[0] if "." in label else label
return stable_name
finally:
# Clean up temp file
tmp_path.unlink(missing_ok=True)
except (OSError, UnicodeDecodeError, re.error):
# If extraction fails, fall back to filename
# This handles files that don't have \rSec tags or conversion errors
pass
# Fallback: use filename stem
return tex_file.stem
def detect_stable_name_collisions(
self, chapters: list[str], chapter_to_stable: dict[str, str], verbose: bool = False
) -> dict[str, list[str]]:
"""
Detect stable name collisions and group chapters that need to be merged.
When multiple source files have the same stable name prefix (e.g., classes.tex,
access.tex, derived.tex all have 'class' prefix), they must be merged into a
single output file to avoid data loss.
This happens in older C++ standards (C++11/n3337) where topics were split across
multiple files but later consolidated.
Args:
chapters: Ordered list of chapter names from std.tex
chapter_to_stable: Mapping from chapter name to stable name
verbose: Print collision information
Returns:
Dictionary mapping stable_prefix -> [ordered_list_of_chapters]
Only includes entries with 2+ chapters (collision groups)
Example:
Input:
chapters = ['classes', 'derived', 'access', 'declarations', 'declarators']
chapter_to_stable = {'classes': 'class', 'derived': 'class', 'access': 'class',
'declarations': 'dcl', 'declarators': 'dcl'}
Output:
{'class': ['classes', 'derived', 'access'],
'dcl': ['declarations', 'declarators']}
"""
# Group chapters by stable name
stable_to_chapters = {}
for chapter in chapters:
stable_name = chapter_to_stable.get(chapter)
if not stable_name:
continue
if stable_name not in stable_to_chapters:
stable_to_chapters[stable_name] = []
stable_to_chapters[stable_name].append(chapter)
# Find collision groups (stable names with 2+ chapters)
collision_groups = {
stable: chapters_list
for stable, chapters_list in stable_to_chapters.items()
if len(chapters_list) > 1
}
if verbose and collision_groups:
print(f"\nDetected {len(collision_groups)} stable name collision(s):")
for stable_name, chapters_list in collision_groups.items():
print(f" {stable_name}: {len(chapters_list)} files will be merged")
for chapter in chapters_list:
print(f" - {chapter}.tex")
return collision_groups
def _merge_tex_files(self, chapter_files: list[Path], verbose: bool = False) -> Path:
r"""
Merge multiple LaTeX files into a single temporary file.
Concatenates the content of multiple .tex files in order, preserving
all \rSec0, \label{}, and other LaTeX commands. The merged file can
then be converted as a single unit.
Args:
chapter_files: Ordered list of .tex files to merge
verbose: Print merge information
Returns:
Path to temporary file containing merged content
"""
if verbose:
print(f" Merging {len(chapter_files)} files:")
for f in chapter_files:
print(f" + {f.name}")
# Concatenate file contents with separators
merged_content = []
for tex_file in chapter_files:
content = tex_file.read_text(encoding="utf-8")
merged_content.append(content)
# Create temporary file with merged content
# Join with double newline to ensure proper spacing
return create_temp_tex_file("\n\n".join(merged_content))
def build_full_standard(
self, converter, output_file: Path, verbose: bool = False, toc_depth: int = 1
) -> tuple[str, list[str]]:
"""
Build complete standard by converting chapters in order and concatenating.
Args:
converter: LatexToMarkdownConverter instance
output_file: Path to write complete standard
verbose: Print progress messages
toc_depth: Maximum heading depth for table of contents (1=H1 only, 2=H1+H2, etc.)
Returns:
Tuple of (markdown_content, list of converted chapters)
"""
chapters = self.extract_chapter_order()
if verbose:
print(f"Found {len(chapters)} chapters in std.tex")
# Convert .dot diagrams to SVG before processing chapters
# Images go in the same directory as the output file
output_dir = Path(output_file).parent
ensure_dir(output_dir)
self.convert_diagrams_to_svg(output_dir, verbose=verbose)
converted_chapters = []
all_content_parts = []
all_references = {} # Collect all references from all chapters
temp_files = [] # Track temporary files for cleanup
for i, chapter in enumerate(chapters, 1):
chapter_file = self.draft_dir / f"{chapter}.tex"
if not chapter_file.exists():
if verbose:
print(f"Warning: {chapter}.tex not found, skipping")
continue
if verbose:
print(f"[{i}/{len(chapters)}] Converting {chapter}.tex...")
# Expand \input{} commands for chapters that use them
# (front.tex and back.tex contain \input{} references)
file_to_convert = chapter_file
if chapter in ["front", "back"]:
try:
file_to_convert = self._expand_input_commands(chapter_file)
temp_files.append(file_to_convert)
except Exception as e:
if verbose:
print(f"Warning: Could not expand inputs in {chapter}.tex: {e}")
# Convert chapter to markdown
try:
markdown = converter.convert_file(
file_to_convert,
output_file=None, # Return as string
standalone=False, # Don't include standalone wrappers
verbose=False,
source_dir=self.draft_dir,
)
# Extract link definitions and content separately
content, references = self._split_content_and_references(markdown)
all_content_parts.append(content)
all_references.update(references)
converted_chapters.append(chapter)
except Exception as e:
# Always print conversion errors to prevent silent failures
print(f"ERROR: Failed to convert {chapter}.tex: {e}", file=sys.stderr)
if verbose:
import traceback
traceback.print_exc()
continue
# Build final document
full_content = "\n\n---\n\n".join(all_content_parts)
# Generate and prepend Table of Contents
toc = self._generate_toc(full_content, max_depth=toc_depth)
full_content = toc + "\n\n---\n\n" + full_content
# Add all link definitions at the end
if all_references:
link_defs = "\n<!-- Link reference definitions -->\n"
for ref in sorted(all_references.keys()):
link_defs += f"[{ref}]: #{ref}\n"
full_content += "\n\n" + link_defs
# Write to output file
output_file.write_text(full_content, encoding="utf-8")
# Cleanup temporary files
cleanup_temp_files(temp_files)
if verbose:
print(f"\nWrote complete standard to {output_file}")
print(f"Converted {len(converted_chapters)}/{len(chapters)} chapters")
print(f"Total cross-references: {len(all_references)}")
return full_content, converted_chapters
def _generate_toc(self, markdown_content: str, max_depth: int = 1) -> str:
"""
Generate a Table of Contents from markdown headings.
Extracts headings with format: # Title <a id="label">[label]</a>
Generates TOC entries with format: <section num> <title> [<stable name>]
Args:
markdown_content: Full markdown content with headings
max_depth: Maximum heading depth to include (1=H1 only, 2=H1+H2, etc.)
Returns:
TOC as a string
"""
toc_lines = []
toc_lines.append("# Table of Contents\n")
# Pattern to match headings with embedded anchors
# Matches: ## Title <a id="label">[[label]]</a>
heading_pattern = re.compile(
r'^(#{1,6})\s+(.+?)\s+<a id="([^"]+)">\[\[([^\]]+)\]\]</a>\s*$', re.MULTILINE
)
# Track section numbers at each level
section_numbers = [0, 0, 0, 0, 0, 0] # Support up to H6
for match in heading_pattern.finditer(markdown_content):
hashes = match.group(1)
title = match.group(2).strip()
stable_name = match.group(4)
level = len(hashes) - 1 # H1=0, H2=1, etc.
# Update section numbers (always update for correct numbering)
section_numbers[level] += 1
# Reset deeper levels
for i in range(level + 1, 6):
section_numbers[i] = 0
# Skip headings deeper than max_depth
if level >= max_depth:
continue
# Build section number string (e.g., "1.2.3")
section_num = ".".join(str(section_numbers[i]) for i in range(level + 1))
# Create TOC entry with indentation
indent = " " * level
list_marker = "- "
toc_entry = (
f"{indent}{list_marker}{section_num} {title} [[{stable_name}]](#{stable_name})"
)
toc_lines.append(toc_entry)
return "\n".join(toc_lines)
def _split_content_and_references(self, markdown: str) -> tuple[str, dict]:
"""
Split markdown into content and link reference definitions.
Returns:
Tuple of (content, dict of references)
"""
lines = markdown.split("\n")
content_lines = []
references = {}
in_references = False
for line in lines:
if "<!-- Link reference definitions -->" in line:
in_references = True
continue
if in_references:
# Match [ref]: #ref pattern
match = re.match(r"\[([^\]]+)\]:\s*#\1", line)
if match:
references[match.group(1)] = True
continue
content_lines.append(line)
return "\n".join(content_lines).strip(), references
def _generate_toc_for_separate_files(self, output_files: list[Path], max_depth: int = 1) -> str:
"""
Generate a Table of Contents with links to separate markdown files.
Similar to _generate_toc() but generates cross-file links:
[intro.scope](intro.md#intro.scope) instead of [intro.scope](#intro.scope)
Args:
output_files: List of output markdown files
max_depth: Maximum heading depth to include (1=H1 only, 2=H1+H2, etc.)
Returns:
TOC as a string with cross-file links
"""
toc_lines = []
toc_lines.append("# Table of Contents\n")
# Pattern to match headings with embedded anchors
# Matches: ## Title <a id="label">[[label]]</a>
# Also matches annexes: ## Title (informative) <a id="label" data-annex="true" data-annex-type="informative">[[label]]</a>
heading_pattern = re.compile(
r'^(#{1,6})\s+(.+?)\s+<a id="([^"]+)"(?:\s+[^>]+)?>\[\[([^\]]+)\]\]</a>\s*$',
re.MULTILINE,
)
# Separate pattern to detect if heading is an annex and extract type
annex_pattern = re.compile(r'data-annex="true"(?:\s+data-annex-type="([^"]+)")?')
# Track section numbers at each level
section_numbers = [0, 0, 0, 0, 0, 0] # Support up to H6
annex_counter = 0 # Track annex letter (A, B, C, etc.)
current_annex_letter = None # Track current annex for subsections
# Process files in order
for md_file in output_files:
content = md_file.read_text(encoding="utf-8")
filename = md_file.stem
for match in heading_pattern.finditer(content):
hashes = match.group(1)
title = match.group(2).strip()
anchor_id = match.group(3)
stable_name = match.group(4)
# Check if this heading is an annex (has data-annex="true")
full_match = match.group(0)
is_annex = annex_pattern.search(full_match) is not None
level = len(hashes) - 1 # H1=0, H2=1, etc.
# For annex headings at H1 level, use letter numbering
if is_annex and level == 0:
annex_counter += 1
current_annex_letter = chr(ord("A") + annex_counter - 1)
# Reset annex subsection numbering
for i in range(1, 6):
section_numbers[i] = 0
else:
# Update section numbers (always update for correct numbering)
section_numbers[level] += 1
# Reset deeper levels
for i in range(level + 1, 6):
section_numbers[i] = 0
# Skip headings deeper than max_depth
if level >= max_depth:
continue
# Build section number string
if is_annex and level == 0:
# Annex A, B, C, etc.
section_num = f"Annex {current_annex_letter}"
elif current_annex_letter and level > 0:
# Annex subsections: A.1, A.2, etc.
subsection = ".".join(str(section_numbers[i]) for i in range(1, level + 1))
section_num = f"{current_annex_letter}.{subsection}"
else:
# Regular numbered sections: 1.2.3, etc.
section_num = ".".join(str(section_numbers[i]) for i in range(level + 1))
# Create TOC entry with cross-file link
indent = " " * level
list_marker = "- "
# Format: - section_num title [[stable_name]](filename.md#anchor)
toc_entry = f"{indent}{list_marker}{section_num} {title} [[{stable_name}]]({filename}.md#{anchor_id})"
toc_lines.append(toc_entry)
return "\n".join(toc_lines)
@staticmethod
def _is_grammar_definition(block: str) -> bool:
"""
Check if a BNF block contains a grammar definition (nonterminal:).
Grammar definitions have lines like "nonterminal-name:" that define
production rules. Example/explanation blocks (like "behaves as if")
don't have these and should be excluded from grammar.md.
Args:
block: Content of a BNF code block
Returns:
True if block contains at least one grammar definition
"""
# Pattern: lowercase word (with optional hyphens/digits), followed by colon
# at the start of a line. Examples: "declaration:", "namespace-alias-definition:"
return bool(re.search(r"^[a-z][a-z0-9-]*:", block, re.MULTILINE))
def _generate_grammar_appendix(
self, output_files: list[Path], output_dir: Path, verbose: bool = False
) -> None:
"""
Generate complete grammar.md by aggregating BNF blocks from all chapter files.
Scans all converted chapter files, extracts BNF code blocks, groups them by
source file, and writes a complete grammar appendix to grammar.md.
This replaces the stub grammar.md (which only contains intro and keywords)
with a complete grammar summary containing ~500 BNF blocks from all chapters.
Args:
output_files: List of converted chapter markdown files
output_dir: Directory containing output files
verbose: Print progress messages
"""
# Mapping of stable names to grammar section info (from LaTeX \gramSec commands)
# Order matches the sequence in which \gramSec appears in the LaTeX sources
grammar_sections = [
("lex", "Lexical conventions"),
("basic", "Basic concepts"),
("expr", "Expressions"),
("stmt", "Statements"),
("dcl", "Declarations"),
("class", "Classes"),
("over", "Overloading"),
("temp", "Templates"),
("cpp", "Preprocessing directives"),
("except", "Exception handling"),
("depr", "Deprecated features"),
]
# Pattern to extract BNF code blocks: ``` bnf\n...\n```
bnf_pattern = re.compile(r"^``` bnf\n(.*?)\n```$", re.MULTILINE | re.DOTALL)
# Collect BNF blocks by stable name
bnf_by_file = {}
file_by_stem = {f.stem: f for f in output_files}
for stable_name, section_title in grammar_sections:
if stable_name in file_by_stem:
md_file = file_by_stem[stable_name]
content = md_file.read_text(encoding="utf-8")
# Extract BNF blocks that contain grammar definitions
# Filter out example/explanation blocks (like "behaves as if")
all_blocks = bnf_pattern.findall(content)
blocks = [b for b in all_blocks if self._is_grammar_definition(b)]
if blocks:
bnf_by_file[stable_name] = {
"title": section_title,
"blocks": blocks,
"count": len(blocks),
}
if verbose:
print(f" Extracted {len(blocks)} BNF blocks from {stable_name}.md")
# Find grammar.md in output files
grammar_file = output_dir / "grammar.md"
if not grammar_file.exists():
if verbose:
print("Warning: grammar.md not found, skipping grammar aggregation")
return
# Read current grammar.md to preserve intro and keywords sections
current_content = grammar_file.read_text(encoding="utf-8")
# Extract everything up to and including the Keywords section
# Grammar.md has: ## General, ## Keywords with 6 BNF blocks, then other sections
# We want to preserve General + Keywords only, then replace everything else with aggregated sections
# Find "## Keywords" and then the next "##" heading after it
keywords_match = re.search(r"^## Keywords", current_content, re.MULTILINE)
if keywords_match:
# Find the next ## heading after Keywords
next_heading = re.search(
r"^##\s", current_content[keywords_match.end() :], re.MULTILINE
)
if next_heading:
# Extract up to (but not including) the next heading
intro_and_keywords = current_content[: keywords_match.end() + next_heading.start()]
else:
# No next heading found, use entire content (shouldn't happen)
intro_and_keywords = current_content
else:
# Fallback: if we can't find Keywords, just use first two headings
header_parts = current_content.split("\n## ", 3)
if len(header_parts) >= 3:
intro_and_keywords = "\n## ".join(header_parts[:3])
else:
intro_and_keywords = current_content
# Build new grammar.md content
new_content_parts = [intro_and_keywords.rstrip()]
# Add aggregated grammar sections
total_blocks = 0
aggregated_anchors = [] # Track anchors for link definitions
for stable_name, section_title in grammar_sections:
if stable_name in bnf_by_file:
section_info = bnf_by_file[stable_name]
blocks = section_info["blocks"]
total_blocks += len(blocks)
# Add section heading with anchor
anchor_id = f"gram.{stable_name}"
aggregated_anchors.append(anchor_id)
new_content_parts.append(
f'\n\n## {section_title} <a id="{anchor_id}">[[{anchor_id}]]</a>\n'
)
# Add all BNF blocks from this section with spacing between them
for block in blocks:
new_content_parts.append(f"\n``` bnf\n{block}\n```\n")
# Add link definitions for aggregated sections
if aggregated_anchors:
new_content_parts.append("\n<!-- Link reference definitions -->\n")
for anchor_id in aggregated_anchors:
new_content_parts.append(f"[{anchor_id}]: #{anchor_id}\n")
# Write updated grammar.md
new_content = "".join(new_content_parts)
grammar_file.write_text(new_content, encoding="utf-8")
if verbose:
print(
f"\nRegenerated grammar.md with {total_blocks} BNF blocks from {len(bnf_by_file)} sections"
)
def build_separate_chapters(
self,
converter,
output_dir: Path,
verbose: bool = False,
toc_depth: int = 1,
) -> list[Path]:
"""
Build separate markdown files for each chapter with cross-file linking.
Converts each chapter in std.tex to a separate .md file, then fixes
cross-file reference links so they point to the correct file.
Generates a table of contents and appends it to front.md.
Args:
converter: LatexToMarkdownConverter instance
output_dir: Directory to write chapter markdown files
verbose: Print progress messages
toc_depth: Maximum heading depth for table of contents (1=H1 only, 2=H1+H2, etc.)
Returns:
List of output file paths
"""
chapters = self.extract_chapter_order()
if verbose:
print(f"Found {len(chapters)} chapters in std.tex")
output_dir = Path(output_dir)
ensure_dir(output_dir)
# Convert .dot diagrams to SVG before processing chapters
self.convert_diagrams_to_svg(output_dir, verbose=verbose)
output_files = []
temp_files = [] # Track temporary files for cleanup
chapter_to_stable = {} # Mapping from source filename to stable name
# Pre-extract stable names for all chapters
# This is done upfront to avoid repeated conversions
if verbose:
print("Extracting stable names...")
for chapter in chapters:
chapter_file = self.draft_dir / f"{chapter}.tex"
if chapter_file.exists():
stable_name = self.extract_stable_name_from_tex(chapter_file, converter)
chapter_to_stable[chapter] = stable_name
if verbose and stable_name != chapter:
print(f" {chapter}.tex → {stable_name}.md")
# Detect stable name collisions
collision_groups = self.detect_stable_name_collisions(chapters, chapter_to_stable, verbose)
# Build label index for cross-file references
if verbose:
print("\nBuilding label index for cross-file references...")
from .label_indexer import LabelIndexer
indexer = LabelIndexer(self.draft_dir)
indexer.build_index(use_stable_names=True, stable_name_map=chapter_to_stable)
# Write Lua table file
label_index_file = output_dir / "cpp_std_labels.lua"
indexer.write_lua_table(label_index_file)
if verbose:
stats = indexer.get_statistics()
print(f"Indexed {stats['labels']} labels across {stats['files']} files")
if stats["duplicates"] > 0:
print(f"Warning: Found {stats['duplicates']} duplicate labels")
# Create work units for parallel processing
# Each work unit is either a single chapter or a collision group
work_units = []
processed_chapters = set()
for chapter in chapters:
# Skip if already processed as part of a collision group
if chapter in processed_chapters:
continue
chapter_file = self.draft_dir / f"{chapter}.tex"
if not chapter_file.exists():
if verbose:
print(f"Warning: {chapter}.tex not found, skipping")
continue
# Get stable name for this chapter