/
Doxter.pb
1594 lines (1438 loc) · 63.9 KB
/
Doxter.pb
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
;= Doxter: Docs-Generator from PB Sources.
;| Tristano Ajmone, <tajmone@gmail.com>
;| v0.1.4-alpha, October 1, 2018: Public Alpha
;| :License: MIT License
;| :PureBASIC: 5.62
;~------------------------------------------------------------------------------
;| :toclevels: 3
#DOXTER_VER$ = "0.1.4-alpha"
;{******************************************************************************
; ··············································································
; ······························ PureBasic Doxter ······························
; ··············································································
; ******************************************************************************
; AsciiDoc documentation generator from annoted PB source files.
;>description(1)
;| =============================================================================
;| image::doxter_logo.svg[Doxter Logo,align="center"]
;|
;| Doxter is a tool to generate AsciiDoc documentation from PureBasic source
;| files, by using a special notations in comments delimiters to markup tagged
;| regions of text and code that will be exported to an AsciiDoc source document
;| where the various regions will be sorted according to their tag's weight.
;| Released under <<License,MIT License>>.
;|
;| https://github.com/tajmone/doxter
;| =============================================================================
;<
;}******************************************************************************
; * *
;- SETUP
; * *
;{******************************************************************************
; ==============================================================================
; Settings
;{==============================================================================
#SourceDelimiterLen = 80 ; ADoc Source Block delimiters lenght (chars).
#FallbackTag = "region" ; Fallback Tag Id to use when none is provided.
#LineNumDigits = 4 ; Used in Debug output: digits-width of line numbers.
#WeightsDigits = 4 ; Used in Debug output: digits-width of regions' weights.
;}==============================================================================
; Procedures Declarations
;{==============================================================================
Declare ParseFile(SrcFileName.s)
Declare IsAdocComment(codeline.s)
Declare IsSkipComment(codeline.s)
Declare.s StripCommentLine(codeline.s)
Declare ADocSourceStart(weight = 0)
Declare ADocSourceEnd(weight = 0)
Declare Abort(ErrMsg.s)
Declare.s LinePreview(text.s, LineNum = 0, weight = 0, subweight = 0)
Declare.s HeaderLinePreview(text.s, LineNum = 0)
;}==============================================================================
; Internals
;{==============================================================================
;{>Comments_Marks(4100)
;|
;| === Doxter Markers Primer
;|
;| The way Doxter decides which parts of your sorce code to treat as documentation
;| is by means of PureBasic's comment delimiter (`;`) immediately followed by
;| a character which, combined with the delimiter, comprise one of Doxter's
;| markers:
;|
;| .Doxter's Base Markers
;| [cols="7m,23d,70d",separator=¦]
;| |============================================================================
;| ¦ ;= ¦ ADoc Header ¦ Marks beginning of doc Header. (first line only)
;| ¦ ;> ¦ Region Begin ¦ Marks beginning of a tagged region.
;| ¦ ;| ¦ ADoc Comment ¦ Treat line as AsciiDoc text.
;| ¦ ;~ ¦ Skip Comment ¦ The whole line will be ignored and skipped.
;| ¦ ;< ¦ Region End ¦ Marks end of a tagged region.
;| |============================================================================
;|
;| [NOTE]
;| =============================================================================
;| You can freely use PureBasic's special comments marks (`;{`/;`}`/`;-`) within
;| Doxter's markers (e.g. `;{>`, `;}~`, `;-|`, etc.) execpt in the ADoc Header
;| marker, which must be `;=`.
;| This allows you to create regions which are foldable in PureBasic IDE.
;| =============================================================================
;|
;| The *Tagged Region End* marker has an alternative syntax to prevent Doxter
;| from adding an empty line after closing the region:
;|
;| .Region Markers Modifiers
;| [cols="7m,20d,66d"]
;| |============================================================================
;| | ;<< | Unspaced Region End | Don't add empty line after closing tag.
;| |============================================================================
;|
;| This is useful when splitting a paragraph across multiple regions, in order to
;| keep its text lines next to the code they belong to. Without the `<` modifier,
;| Doxter's default behavior would be to add an empty line after the closing
;| region tag, which would split the text in multiple paragraphs in the final
;| document.
;}<
#PB_CommDelim = ";[{}\-]?"
#mrk_RegionStart = #PB_CommDelim + ">"
#mrk_RegionEnd = #PB_CommDelim + "<"
#mrk_ADocLine = #PB_CommDelim + "\|"
#mrk_SkipLine = #PB_CommDelim + "~"
Structure RegionData
Weight.i
Subweight.i
Tag.s
List StringsL.s()
EndStructure
;}==============================================================================
;- RegExs
;{==============================================================================
Enumeration RegExsIDs
#RE_TagRegionBegin
#RE_TagRegionEnd
#RE_ADocComment
#RE_SkipComment
EndEnumeration
#totRegExs = #PB_Compiler_EnumerationValue -1
Restore REGEX_PATTERNS
For i=0 To #totRegExs
Read.s RE_Pattern$
If Not CreateRegularExpression(i, RE_Pattern$)
Debug "ERROR: Couldn't create RegEx #" + Str(i)
End 1
EndIf
Next
DataSection
REGEX_PATTERNS:
Data.s "^\s*?" + #mrk_RegionStart + ; #RE_TagRegionBegin -- Named groups:
"(?<tag>\w*)"+ ; <tag> (optional)
"(\("+ ;
"(?<weight>\d*)?"+ ; <weight> (optional)
"(\.(?<subweight>\d+))?"+ ; <subweight> (optional)
"\))?"
Data.s "^\s*?" + #mrk_RegionEnd + ; #RE_TagRegionEnd -- Named groups:
"(?<modifier>[<]?)" ; <modifier> (optional)
Data.s "^\s*"+ #mrk_ADocLine +" ?(.*)$" ; #RE_ADocComment
Data.s "^\s*"+ #mrk_SkipLine ; #RE_SkipComment
EndDataSection
;}
;}******************************************************************************
; * *
;- MAIN BODY
; * *
;{******************************************************************************
OpenConsole()
PrintN(#Empty$) ; Add empty line to leave prompt behind...
; ==================
; Print Version Info
; ==================
PrintN("Doxter v" + #DOXTER_VER$)
; ==========================
; Get Command Line Parameter
; ==========================
SrcFile.s = ProgramParameter()
;{>CLI_Usage(.10)--------------------------------------------------------------
;|=== Command Line Options
;|
;| To invoke Doxter via command prompt/shell:
;|
;|--------------------
;| doxter <sourcefile>
;|--------------------
;|
;| … where `<sourcefile>` is a PureBasic or SpiderBasic source file.
;}<-----------------------------------------------------------------------------
If SrcFile = #Empty$
Abort("You must supply a filename")
EndIf
; ===============================
;- Check that source file is valid
; ===============================
;{>Input_File_Validation(3300)--------------------------------------------------
;| === Input File Validation
;|
;| Doxter checks that the passed `<sourcefile>` parameter has a valid extension:
;|
;| * `.pb` -- PureBasic source file.
;| * `.pbi` -- PureBasic include file.
;| * `.pbf` -- PureBasic form file.
;| * `.sb` -- SpiderBasic source file.
;|
;| If the file extension doesn't match, Doxter will report an error and abort
;| with Status Error 1.
;}<-----------------------------------------------------------------------------
SrcExt.s = GetExtensionPart(SrcFile)
Select LCase(SrcExt)
Case "pb", "pbi", "pbf", "sb"
ValidExt = #True
EndSelect
If Not ValidExt
Abort(~"Invalid file extension \"."+ SrcExt +~"\". Only PB and SB files accepted.")
EndIf
;{>Input_File_Validation -------------------------------------------------------
;| Doxter will also check that the file exists, it's not a directory, and it's
;| not 0 Kb in size; and abort with Status Error if any of these are met.
;}<-----------------------------------------------------------------------------
Select FileSize(SrcFile)
Case 0
Abort(~"File is 0 Kb: \""+ SrcFile +~"\"")
Case -1
Abort(~"File not found: \""+ SrcFile +~"\"")
Case -2
Abort(~"Parameter is a directory: \""+ SrcFile +~"\"")
EndSelect ;}
NewList RegionsL.RegionData()
NewList HeaderL.s()
ParseFile(SrcFile)
; =================
;- Print Resume Info
; =================
totRegions = ListSize(RegionsL())
PrintN("Total tagged regions found: "+ Str(totRegions))
OutFile.s = SrcFile
If ListSize(HeaderL())
; ----------------------------
; Document Has AsciiDoc Header
; ----------------------------
;{>Output_File(3330)
;|
;| Depending on whether the source file contains or not an <<AsciiDoc Header>>,
;| the output file will be named either `<sourcefile>.asciidoc` or
;| `<sourcefile>.adoc`, respectively.
;| At parsing completion, Doxter will inform the user wther it found a Header
;| or not, and print the output filename to the console.
;|
;| This differentiation in the extension used in the output file is due to
;| the conventions and needs of the PureBasic CodeArchiv project, where files
;| with `.asciidoc` extension are considered stand-alone documents, which are
;| subject to script-automated conversion to HTML; whereas files with `.adoc`
;| extension are considered snippets file which are imported by other docs.
;| Beside the different file extensions, both type of output files are formated
;| as standard AsciiDoc documents (with Asciidoctor Ruby in mind).
;|
;| This is inline with the AsciiDoc standard which demands the presence of a
;| document Header in a source file for it to be buildable as a standalone
;| doc; and with the common practice of splitting large documents in smaller
;| files, which are then imported into the main document and therefore don't
;| need a Header of their own.
;}<---------------------------------------------------------------------------
DocHeader = #True
Print("Document has Header, ")
; use ".asciidoc" extension for standalone docs in CodeArchiv
OutExt.s = "asciidoc"
Else
Print("Document dosesn't contain a Header, ")
OutExt.s = "adoc"
EndIf
PrintN(~"it will be saved with \"." + OutExt +~"\" extension.")
OutFile = ReplaceString(OutFile, SrcExt, OutExt)
PrintN("outfile: " + OutFile)
; ================
;- Save Output File
; ================
If Not CreateFile(0, OutFile, #PB_UTF8)
Abort("Couldn't open output file for writing: "+ OutFile)
EndIf
If DocHeader
; --------------------
; Write Header to File
; --------------------
ForEach HeaderL()
If Not WriteStringN(0, HeaderL())
Abort("Couldn't write to file: "+ OutFile)
EndIf
Next
; Add blank line after Header
If Not WriteStringN(0, #Empty$)
Abort("Couldn't write to file: "+ OutFile)
EndIf
EndIf
; ----------------------------
; Write Tagged Regions to File
; ----------------------------
ForEach RegionsL()
With RegionsL()
ForEach \StringsL()
If Not WriteStringN(0, \StringsL())
Abort("Couldn't write to file: "+ OutFile)
EndIf
Next
EndWith
Next
; Add empty line at EOL
If Not WriteStringN(0, #Empty$)
Abort("Couldn't write to file: "+ OutFile)
EndIf
CloseFile(0)
CloseConsole()
End 0
;}******************************************************************************
; * *
;- PROCEDURES
; * *
;{******************************************************************************
Procedure ParseFile(SrcFileName.s)
;{>two_steps_parsing(4210)
;~----------------------------------------------------------------------------
;| Doxter uses a two-steps parsing approach when processing documents:
;|
;| 1. *Header Parser* -- Scans the first lines of the source file looking for
;| an AsciiDoc Header. Whether or not it found an Header, once finished
;| its job the Header Parser relinquishes control over to the Regions Parser.
;| 2. *Regions Parser* -- Scans the reaminder of the source file looking for
;| tagged regions to extract.
;|
;| These are two different parsers altogether, and Doxter always runs the fed
;| source file against both of them, in the exact order specified above.
;}<---------------------------------------------------------------------------
Shared RegionsL()
Shared HeaderL()
If Not ReadFile(0, SrcFileName)
Abort(~"Couldn't open source file \"" + SrcFileName + ~"\" for reading.")
End 1
EndIf
BOM = ReadStringFormat(0) ; Skip BOM!
; TODO: Could implement read opearions using file format from BOM! (currently only UTF-8 supported)
PrintN("Parsing source file: " + SrcFileName)
PrintN(LSet(#Empty$, 80, "="))
; ============
;- Parser Setup
; ============
;{>Regions_Parser_Modalities(4242)
;~----------------------------------------------------------------------------
;| The *Regions Parser* alternates between two mutually exclusive modalities:
;| _Seeking_, and _InsideRegion_.
;|
;| When in _Seeking_ modality, the parser will scan every source line until it
;| finds a line whose first non-whitespace characters are a Region Begin marker
;| (`;>` or `;{>`), and it will ignore anything else. Once it finds the Region
;| Begin marker the parser switches to the _InsideRegion_ modality.
;|
;| When in _InsideRegion_ modality, the parser behavior changes, as every line
;| which has not a Skip Comment marker (`;~`) will be processed and become part
;| of the output document, until it find a Region End marker (`;<` and variants),
;| in which case it reverts to _Seeking_ modality, and so on, until the end of
;| file is reached.
;|
;| Furthermore, in _InsideRegion_ modality the parser can be enter and exit the
;| _InsideCode_ state. This is used to track inclusion of source code lines in
;| the region, as opposed to ADoc comment lines, for in the final document
;| source code must be enclosed in an AsciiDoc source block, using source
;| delimiters and setting the syntax to PureBasic. This will ensure that code
;| is shown as a verbatim block and enable syntax highlighting (if supported).
;}<---------------------------------------------------------------------------
Enumeration ParseStates
#Seeking
#InsideRegion
EndEnumeration
; Regions-Tracking Map
;{====================
; The parser uses this map to track the last weights used for every region.
; Wether the weights were defined in the Region Marker or were auto-generated,
; this map will always keep track of the last eights used during parsing.
; Region names are case sensitive in Asciidoctor (and PureBasic Map keys too).
Structure RegionTracking
weight.i ; Last weight used for region tag.
subweight.i ; Last subweight used for region tag.
count.i ; Tracks number of same-named regions found
EndStructure
NewMap RegionsTrackM.RegionTracking()
;}
cntLine = 1
ParserState = #Seeking
currTag.s = #Empty$
currWeight = 0 ; Will be used as fallback value (+1) if first tag ha no weight
AddingCode = #False
FallbackCnt = 1 ; Counter to append to #FallbackTag in unamed tags.
; ==============================================================================
;- THE HEADER PARSER
; ==============================================================================
;{>Header_Parser_Rules(4230)
;|
;| ==== Header Parser Rules
;|
;| The *Header Parser* has one single task, detect if the source contains an
;| AsciiDoc Header and, if there is one, extract it and store it in memory.
;|
;| * Check if the very first line of the source file starts with `;=` (no
;| leading space allowed):
;| ** *No*? Reset file pointer position to beginning of file and relinquish
;| control to the Regions Parser. (Quit Parsing)
;| ** *Yes*? Then an AsciiDoc Header was found; strip away the `;` and store
;| the line in the Header's data storage, then:
;| *** (_loop entrypoint_) Store current file position pointer and parse the
;| next line:
;| **** If an ADoc Comment line (`;|`) is found, strip it of the marker and
;| add it to Header's data storage, then carry on with parsing loop.
;| **** If a Skip Comment line (`;~`) is found, ignore it and carry on with
;| parsing loop.
;| **** If the parsed line is none of the above, restore previous file position
;| from stored pointer and relinquish control to the Regions Parser.
;| (Exit Loop, Quit Parsing)
;}<---------------------------------------------------------------------------
; If the first line starts with ";=" then it's an AsciiDoc Header
FilePos = Loc(0) ; Store current position in case we need to rollback
firstline.s = ReadString(0)
If Left(firstline, 2) = ";="
; ============
; Header found
; ============
; LineNum$ = RSet(Str(cntLine), #LineNumDigits, "0") + "|"
AddElement(HeaderL())
HeaderL() = Right(firstline, Len(firstline)-1)
HeaderLinePreview(HeaderL(), cntLine)
cntLine +1
; Now every following ADoc Comment Line we'll be treatd as part of the Header,
; as they might contains the Author and Revision lines, or global settings attributes.
Repeat
FilePos = Loc(0) ; Store current position in case we need to rollback
CurrLine.s = ReadString(0)
If IsSkipComment(CurrLine)
; Skip Comment Lines are allowed, just ignore them and carry on parsing.
cntLine +1
ElseIf IsAdocComment(CurrLine)
AddElement(HeaderL())
HeaderL() = StripCommentLine(CurrLine)
HeaderLinePreview(HeaderL(), cntLine)
cntLine +1
Else
; Rollback file position and exit loop
FileSeek(0, FilePos, #PB_Absolute)
Break
EndIf
ForEver
Else
; ===============
; No Header found
; ===============
; Rollback file position and exit loop
FileSeek(0, FilePos, #PB_Absolute)
EndIf
; ==============================================================================
;- THE REGIONS PARSER
; ==============================================================================
;{>Regions_Parser_Rules1(4240)
;|
;| ==== Regions Parser Rules
;|
;| The task of the *Regions Parser* is to extract and process all lines that
;| are enclosed between Region Start and Region End tags, and store them in
;| memory.
;<
;>Regions_Parser_Rules2(4244)
;|
;| * (*Seeking Modality*) this is the modality the parser starts off in:
;| ** (_loop entrypoint_) Parse line and check if its first non-white space
;| characters are a Region Begin Tag (`;>`):
;| *** *No*? Ignore line and carry on with parsing parsing loop in Seeking mode.
;| *** *Yes*?
;| **** Process line and extract _tag_, _weight_ and _subweight_ (if present):
;| ***** if no _tag_ was provided, use default fallback Id instead: `region`
;| followed by a counter that increases at each use (e.g. `region1`,
;| `region2`, etc.).
;| ***** if no _weight_ was provided:
;| ****** if a region with same _tag_ already exists in memory, retrive its
;| weight and use it, otherwise assign the last used weigth incremented
;| by one (assume that the users wishes the new region to be continguos
;| with the preceding one).
;| ***** if no _subweight_ was provided:
;| ****** if a region with same _tag_ already exists in memory, retrive its
;| last used subweight, increase by 1 and use it, otherwise use value 1.
;| **** Create new entry in memory for this region fragment and store its weight
;| and subweight values.
;| **** Enter _InsideRegion_ modality (Switch Loop).
;| * (*InsideRegion Modality*):
;| ** (_loop entrypoint_) Parse line and check if its first non-white space
;| characters are one of Doxter markers or not:
;| *** *No*? Then the user wants to include source code lines in the region:
;| **** Set parser's state to _InsideCode_.
;| **** Add to current region's stored data a blank line followed by AsciiDoc
;| markup to open a source block (`[source,purebasic]`) followed by a line
;| with source block delimiter (`---`, 80 chars long).
;| **** Add parsed line to current region's data, as is.
;| **** Carry on parsing loop in InsideRegion modality.
;| *** *Yes*? Depending on the found marker:
;| **** It's an ADoc Comment marker (`;|`):
;| ***** If parser is in _InsideCode_ state, add to current region's stored data
;| an AsciiDoc line containing a source delimiter to end source code
;| block, followed by a blank line. Carry on parsing loop.
;| ***** Strip marker away (together with following space character, if present)
;| and add line to current region's data storage in memory.
;| ***** Carry on parsing loop in InsideRegion modality.
;| **** It's a Skip Comment marker (`;~`):
;| ***** Ignore line and carry on parsing loop in InsideRegion modality.
;| **** It's a Region End marker (`;<`):
;| ***** If parser is in _InsideCode_ state, add to current region's stored data
;| an AsciiDoc line containing a source delimiter to end source code
;| block, followed by a blank line. Carry on parsing loop.
;| ***** Check if the Region End marker contais the `<` modifier (`;<<`);
;| if not, add a blank line to current region, otherwise not.
;| ***** Revert to _Seeking_ modality (Switch Loop).
;|
;| [NOTE]
;| ===========================================================================
;| During the parsing stage no AsciiDoc tagged region begin/end lines are added
;| to the regions stored in memory, because regions with same tag still need
;| to be sorted and merged together (the parser stores each region fragment
;| separately, regardless of its tag).
;| It will be the postprocessor's job to handle all that, and once fragmented
;| regions are merged together the AsciiDoc `// tag:[]` and `// end:[]` lines
;| will be added at their start and end, respectively.
;|
;| The AsciiDoc `// tag:[]` and `// end:[]` lines shown in the Live Preview
;| are just for debugging purposes, so to speak, but they are not actually
;| stored in memory at that point.
;| ===========================================================================
;|
;}<---------------------------------------------------------------------------
; Scan every line of the source file until EOF
While Eof(0) = 0
CurrLine.s = ReadString(0)
; TODO: optimize: Use a RegEx to check if any marker matches, instead of multiple checks.
Select ParserState
Case #Seeking
; ~~~~~~~~~~~~~~~~~~~~~~~~~
; Parser Looking for Tag...
; ~~~~~~~~~~~~~~~~~~~~~~~~~
If MatchRegularExpression(#RE_TagRegionBegin, CurrLine)
; =========================
;- Region Start Marker Found
; =========================
ParserState = #InsideRegion
If ExamineRegularExpression(#RE_TagRegionBegin, CurrLine)
NextRegularExpressionMatch(#RE_TagRegionBegin)
; ///// Establish Region's Tag /////
currTag = RegularExpressionNamedGroup(#RE_TagRegionBegin, "tag")
If currTag = #Empty$
; No Tag ID found, create one:
; ----------------------------
currTag = #FallbackTag + Str(FallbackCnt)
FallbackCnt +1
EndIf
RegionIsNotNew = FindMapElement(RegionsTrackM(), currTag) ; NOTE: Map keys are case-sensitive!
; ///// Establish Region's Weight /////
parsedWeight.s = RegularExpressionNamedGroup(#RE_TagRegionBegin, "weight")
If parsedWeight = #Empty$
; No Tag Weight found, auto-generate it
; -------------------------------------
If RegionIsNotNew ; retrive its last used weight.
currWeight = RegionsTrackM()\weight
Else ; It's a new region, assign it the last used weight + 1.
; (assume author wants it to be after last used region)
currWeight +1
EndIf
Else
currWeight = Val(parsedWeight)
EndIf
; ///// Establish Region's Subweight /////
parsedSubweight.s = RegularExpressionNamedGroup(#RE_TagRegionBegin, "subweight")
If parsedSubweight = #Empty$
; No Tag Subweight found, auto-generate it
; -------------------------------------
If RegionIsNotNew ; retrive its last used Subweight And add 1 To it.
currSubweight = RegionsTrackM(currTag)\Subweight +1
Else ; It's a new region, assign it default Subweight = 1.
currSubweight = 1
EndIf
Else
currSubweight = Val(parsedSubweight)
EndIf
EndIf
; ----------------------------
; Add New Region to List
; ----------------------------
AddElement(RegionsL())
With RegionsL()
\Tag = currTag
\Weight = currWeight
\Subweight = currSubweight
EndWith
; ----------------------------
; Update Regions's Tracker Map
; ----------------------------
RegionsTrackM(currTag)\weight = currWeight
RegionsTrackM(currTag)\subweight = currSubweight
; Increase counter of this region
RegionsTrackM(currTag)\count +1
; ------------------------------
; AsciiDoc Tag Open Line Preview
; ------------------------------
; Just show the tag in Line Previewer, don't add it to region's data.
LinePreview("// tag::"+ currTag + "[]", cntLine, currWeight, currSubweight)
Else
; ===================
; Ignore Current Line
; ===================
EndIf
Case #InsideRegion
; ~~~~~~~~~~~~~~~~~~~~~~~~~
; Carry-On Tag Parsing...
; ~~~~~~~~~~~~~~~~~~~~~~~~~
If MatchRegularExpression(#RE_TagRegionEnd, CurrLine)
; =======================
;- Region End Marker Found
; =======================
ParserState = #Seeking
If ExamineRegularExpression(#RE_TagRegionEnd, CurrLine)
NextRegularExpressionMatch(#RE_TagRegionEnd)
modifier.s = RegularExpressionNamedGroup(#RE_TagRegionEnd, "modifier")
; If there was an open source block close it:
If AddingCode
ADocSourceEnd(currWeight)
AddingCode = #False
EndIf
; AsciiDoc Tag End Line Preview
; ------------------------------
LinePreview("// end::"+ currTag + "[]", cntLine, currWeight, currSubweight)
If Not modifier = "<"
; Add blank line to ensure ADoc contents integrity.
With RegionsL()
AddElement(\StringsL())
\StringsL() = #Empty$
LinePreview(\StringsL(), 0, currWeight, currSubweight)
EndWith
EndIf
EndIf
; EndWith ; DELME
currTag = #Empty$
Else
; ===================================
; Add Curr Line to Curr Tagged Region
; ===================================
If LTrim(CurrLine) = #Empty$
; -----------------------
;- Curr Line Is Whitespace
; -----------------------
With RegionsL()
AddElement(\StringsL())
\StringsL() = CurrLine
LinePreview(\StringsL(), cntLine, currWeight, currSubweight)
EndWith
Else
If IsAdocComment(CurrLine)
; ------------------------------
;- Curr Line Is ADoc Comment Line
; ------------------------------
If AddingCode ; Check if we were adding source code to contents
ADocSourceEnd(currWeight) ; Add closing source block delimiter
AddingCode = #False
EndIf
With RegionsL()
AddElement(\StringsL())
\StringsL() = StripCommentLine(CurrLine)
LinePreview(\StringsL(), cntLine, currWeight, currSubweight)
EndWith
ElseIf IsSkipComment(CurrLine)
; ------------------------------
;- Curr Line Is Skip Comment Line
; ------------------------------
; It's a skip-me comment line (';~'), ignore it
Else
; -----------------
;- Curr Line Is Code
; -----------------
If Not AddingCode
ADocSourceStart(currWeight) ; Add opening source block delimiter
AddingCode = #True
EndIf
With RegionsL()
AddElement(\StringsL())
\StringsL() = CurrLine
LinePreview(\StringsL(), cntLine, currWeight, currSubweight)
EndWith
EndIf
EndIf
EndIf
EndSelect
cntLine +1
Wend
CloseFile(0)
PrintN(LSet(#Empty$, 80, "="))
; ==============================================================================
;- THE REGIONS POSTPROCESSOR
; ==============================================================================
; Now it's time to postprocess extracted regions fragments: merge same-named
; regions and add AsciiDoc region tags.
; =====================
;- Gather Stats and Info
; =====================
totRegionsFrags = ListSize(RegionsL())
PrintN("REGIONS FRAGMENTS: " + Str(totRegionsFrags)) ; DELME
totUniqueRegions = MapSize(RegionsTrackM())
PrintN("UNIQUE REGIONS: " + Str(totUniqueRegions)) ; DELME
; NOTE: This is only for informational purposes, can safely delete.
If totRegionsFrags > totUniqueRegions
PrintN("Regions that need merging, and their total number of parts:")
cnt = 1
With RegionsTrackM()
ForEach RegionsTrackM()
If \count > 1
cnt$ = RSet(Str(cnt)+". ", 7)
PrintN(cnt$ + MapKey(RegionsTrackM()) + " ("+ Str(\count) +")")
cnt +1
EndIf
Next
EndWith
EndIf
; ==================
;- SubRegions Sorting
; ==================
; If there are more region fragments than unique region names we need to merge
; some of them. We must also set all subregions' `\weight` to the last weight
; value found for that region during parsing (i.e. the value stored in
; `RegionsTrackM()\weight`) because in the source there could be multiple
; weight declarations for a same name region but for the final sorting to work
; correctly all subregions must have equal weight.
If totRegionsFrags > totUniqueRegions
PrintN("MERGING REGIONS...") ; DELME
; ---------------------------------------
; 1. Sort regions by Tag, Asciibetically
; ---------------------------------------
SortStructuredList(RegionsL(),
#PB_Sort_Ascending,
OffsetOf(RegionData\Tag),
TypeOf(RegionData\Tag))
; ----------------------------------------------
; 2. Get multipart-regions End and Start indices
; ----------------------------------------------
; Before actually sorting, we'll extract the start and end list-indices of
; each named region that has subregions, and we'll sort them after iterating
; through all the regions, to avoid messing up the iteration.
; We'll need a structured list to track these list indices:
Structure regionIndex
regionStart.i ; index of first unique region element in RegionsL()
regionEnd.i ; index of last unique region element in RegionsL()
EndStructure
NewList RegionsIndexesL.regionIndex()
; Now that regions are asciibetically ordered, let's iterate through them:
ResetList(RegionsL())
With RegionsL()
While NextElement(RegionsL())
subRegions = RegionsTrackM(\Tag)\count
If subRegions > 1 ; This region has sub-regions
; Fix region's weight to last value encountered:
\Weight = RegionsTrackM()\weight
; Store first elements' index
AddElement(RegionsIndexesL())
RegionsIndexesL()\regionStart = ListIndex(RegionsL())
; Now cycle through up to last element
For skip=1 To subRegions -1
NextElement(RegionsL())
; Fix region's weight to last value encountered:
\Weight = RegionsTrackM()\weight
Next
; Store last elements' index
RegionsIndexesL()\regionEnd = ListIndex(RegionsL())
EndIf
Wend
EndWith
With RegionsIndexesL()
; ----------------------------------------------
; 3. Subsort same-named regions by subWeight
; ----------------------------------------------
ForEach RegionsIndexesL()
SortStructuredList(RegionsL(), #PB_Sort_Ascending,
OffsetOf(RegionData\Subweight),
TypeOf(RegionData\Subweight),
\regionStart, \regionEnd)
Next
EndWith
Else
PrintN("NO REGIONS MERGING REQUIRED") ; DELME
EndIf
; ===============
;- Add Region Tags
; ===============
PrintN(LSet("", 20, "-"))
With RegionsL()
ResetList(RegionsL())
While NextElement(RegionsL())
; -----------------------------
; Add AsciiDoc Region Begin Tag
; -----------------------------
FirstElement(\StringsL())
InsertElement(\StringsL())
\StringsL() = "// tag::"+ \Tag + "[]"
; ----------------------
; Skip to Last SubRegion
; ----------------------
; subRegions = RegionsTrackM(\Tag)\count - 1
; For skip = 1 To subRegions
For skip = 1 To RegionsTrackM(\Tag)\count - 1
NextElement(RegionsL())
Next
; ---------------------------
; Add AsciiDoc Region End Tag
; ---------------------------
LastElement(\StringsL())
AddElement(\StringsL())
\StringsL() = "// end::"+ \Tag + "[]"
Wend
EndWith
; ============
;- Sort Regions
; ============
SortStructuredList(RegionsL(), #PB_Sort_Ascending, OffsetOf(RegionData\Weight), TypeOf(RegionData\Weight))
EndProcedure
; ------------------------------------------------------------------------------
Procedure IsAdocComment(codeline.s)
If MatchRegularExpression(#RE_ADocComment, codeline)
ProcedureReturn #True
EndIf
EndProcedure
; ------------------------------------------------------------------------------
Procedure IsSkipComment(codeline.s)
If MatchRegularExpression(#RE_SkipComment, codeline)
ProcedureReturn #True
EndIf
EndProcedure
; ------------------------------------------------------------------------------
Procedure.s StripCommentLine(codeline.s)
If ExamineRegularExpression(#RE_ADocComment, codeline)
NextRegularExpressionMatch(#RE_ADocComment)
ProcedureReturn RegularExpressionGroup(#RE_ADocComment, 1)
EndIf
EndProcedure
; ------------------------------------------------------------------------------
Procedure ADocSourceStart(weight = 0)
Shared RegionsL()
With RegionsL()
AddElement(\StringsL())
\StringsL() = #Empty$
LinePreview(\StringsL(), 0, weight)
AddElement(\StringsL())
\StringsL() = "[source,purebasic]"
LinePreview(\StringsL(), 0, weight)
AddElement(\StringsL())
\StringsL() = LSet(#Empty$, #SourceDelimiterLen, "-")
LinePreview(\StringsL(), 0, weight)
EndWith
EndProcedure
; ------------------------------------------------------------------------------
Procedure ADocSourceEnd(weight = 0)
Shared RegionsL()
With RegionsL()
AddElement(\StringsL())
\StringsL() = LSet(#Empty$, #SourceDelimiterLen, "-")
LinePreview(\StringsL(), 0, weight)
AddElement(\StringsL())
\StringsL() = #Empty$
LinePreview(\StringsL(), 0, weight)
EndWith
EndProcedure
; ------------------------------------------------------------------------------
Procedure Abort(ErrMsg.s)
ConsoleError("ERROR: "+ ErrMsg)
CloseConsole()
End 1
EndProcedure
; ------------------------------------------------------------------------------
Procedure.s LinePreview(text.s, LineNum = 0, weight = 0, subweight = 0)
;{-------------------------------------------------------------------
; Print a preview of the ADoc line, with well formated linenumber and
; tagged region's weight.
; -------------------------------------------------------------------
;{>Parser_Live_Preview(3500)
;|
;| === Parsing Live Preview During Execution
;|
;| During execution, Doxter will output to the console a preview of the parsed
;| lines that belong to tagged regions, showing their ADoc processed version,
;| together with extra lines added by the parser (eg. source code delimiters,
;| blank lines, etc).
;| Although the shown lines are just an aproximation of the final document (the
;| regions will be postprocessed, merged and reoderdered before writing them to
;| file), this feature is very useful to visually trace the source of problems
;| when the ouput results are not as intendend, as the log provides a human
;| friendly insight into Doxter's parser.
;| Here's an example of how the console output looks like:
;| [role="shell"]
;| ----------------------------------------------------------
;||0099|4100| 1|region tag, which would split the text in multiple paragraphs in the final <1>
;||0100|4100| 1|document.
;||0101|4100| 1|// end::Comments_Marks[] <2>
;|| |4100| 1| <3>
;||0169|4101| 10|// tag::CLI_Usage[] <4>
;||0170|4101| 10|=== Command Line Options
;| ----------------------------------------------------------
;|
;| <1> Continuation lines of a region with weight `4100` and subweight `1`.
;| <2> AsciiDoc tagged region `end::` generated by Doxter when it encountered
;| a `;<` marker.
;| <3> Blank line added by Doxter; note that there is no corresponing line
;| number, for it is not found in the source file.
;| <4> Region Being marker found ad line 169, with wieght `4101` and sebweight
;| `10` (probably the continuation of a fragmented region).
;| There are four columns in the preview, representing the line number in the
;| source file, the region's weight, its subweight, and a preview of the line
;| converted to AsciiDoc.
;|
;| The absence of line number in the first column indicates that what you are
;| seeing on the right hand side is a line generated by Doxter, and added to
;| the output document for formatting purposes (e.g. a blank line, source code
;| block delimiters, etc.).
;| The weight colum is very useful when looking at the logged output for it
;| allows to easily spot where regions start and end, as each region should
;| have a different weight (although not mandatory).
;| Header lines will always show the text `head` in the second and third
;| columns, instead of numbers, because the Header has no weight or subweight.
;}<---------------------------------------------------------------------------
If LineNum = 0
LineNum$ = Space(#LineNumDigits)
Else
LineNum$ = RSet(Str(LineNum), #LineNumDigits, "0")
EndIf
If weight = 0
weight$ = Space(#WeightsDigits)
Else
weight$ = RSet(Str(weight), #WeightsDigits, " ")
EndIf
If subweight = 0