coridoc-markdown 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE.txt +21 -0
  3. data/lib/coridoc/markdown/behaviors/admonition.rb +21 -0
  4. data/lib/coridoc/markdown/behaviors/attribute_list.rb +81 -0
  5. data/lib/coridoc/markdown/behaviors/document.rb +34 -0
  6. data/lib/coridoc/markdown/behaviors/extension.rb +69 -0
  7. data/lib/coridoc/markdown/behaviors/heading.rb +33 -0
  8. data/lib/coridoc/markdown/behaviors/math.rb +32 -0
  9. data/lib/coridoc/markdown/behaviors/text.rb +14 -0
  10. data/lib/coridoc/markdown/behaviors.rb +18 -0
  11. data/lib/coridoc/markdown/bindings/captures.rb +145 -0
  12. data/lib/coridoc/markdown/bindings/scope.rb +31 -0
  13. data/lib/coridoc/markdown/bindings.rb +307 -0
  14. data/lib/coridoc/markdown/errors.rb +28 -0
  15. data/lib/coridoc/markdown/lint/registrations.rb +38 -0
  16. data/lib/coridoc/markdown/lint.rb +16 -0
  17. data/lib/coridoc/markdown/model/abbreviation.rb +27 -0
  18. data/lib/coridoc/markdown/model/admonition.rb +33 -0
  19. data/lib/coridoc/markdown/model/attribute_list.rb +25 -0
  20. data/lib/coridoc/markdown/model/base.rb +54 -0
  21. data/lib/coridoc/markdown/model/blockquote.rb +16 -0
  22. data/lib/coridoc/markdown/model/code.rb +11 -0
  23. data/lib/coridoc/markdown/model/code_block.rb +18 -0
  24. data/lib/coridoc/markdown/model/comment.rb +14 -0
  25. data/lib/coridoc/markdown/model/cross_reference.rb +10 -0
  26. data/lib/coridoc/markdown/model/definition_item.rb +26 -0
  27. data/lib/coridoc/markdown/model/definition_list.rb +35 -0
  28. data/lib/coridoc/markdown/model/definition_term.rb +29 -0
  29. data/lib/coridoc/markdown/model/document.rb +33 -0
  30. data/lib/coridoc/markdown/model/emphasis.rb +11 -0
  31. data/lib/coridoc/markdown/model/example_block.rb +21 -0
  32. data/lib/coridoc/markdown/model/extension.rb +23 -0
  33. data/lib/coridoc/markdown/model/footnote.rb +31 -0
  34. data/lib/coridoc/markdown/model/footnote_reference.rb +17 -0
  35. data/lib/coridoc/markdown/model/hard_line_break.rb +18 -0
  36. data/lib/coridoc/markdown/model/heading.rb +17 -0
  37. data/lib/coridoc/markdown/model/highlight.rb +13 -0
  38. data/lib/coridoc/markdown/model/horizontal_rule.rb +11 -0
  39. data/lib/coridoc/markdown/model/image.rb +19 -0
  40. data/lib/coridoc/markdown/model/link.rb +19 -0
  41. data/lib/coridoc/markdown/model/list.rb +22 -0
  42. data/lib/coridoc/markdown/model/list_item.rb +14 -0
  43. data/lib/coridoc/markdown/model/literal.rb +16 -0
  44. data/lib/coridoc/markdown/model/math.rb +21 -0
  45. data/lib/coridoc/markdown/model/named_value.rb +18 -0
  46. data/lib/coridoc/markdown/model/open_block.rb +17 -0
  47. data/lib/coridoc/markdown/model/paragraph.rb +15 -0
  48. data/lib/coridoc/markdown/model/pass.rb +16 -0
  49. data/lib/coridoc/markdown/model/sidebar.rb +18 -0
  50. data/lib/coridoc/markdown/model/strikethrough.rb +13 -0
  51. data/lib/coridoc/markdown/model/strong.rb +11 -0
  52. data/lib/coridoc/markdown/model/subscript.rb +9 -0
  53. data/lib/coridoc/markdown/model/superscript.rb +9 -0
  54. data/lib/coridoc/markdown/model/table.rb +13 -0
  55. data/lib/coridoc/markdown/model/text.rb +13 -0
  56. data/lib/coridoc/markdown/model/underline.rb +9 -0
  57. data/lib/coridoc/markdown/model/verse.rb +20 -0
  58. data/lib/coridoc/markdown/parser/ast_processor.rb +541 -0
  59. data/lib/coridoc/markdown/parser/attribute_lists.rb +48 -0
  60. data/lib/coridoc/markdown/parser/block_parser.rb +735 -0
  61. data/lib/coridoc/markdown/parser/frontmatter_parser.rb +23 -0
  62. data/lib/coridoc/markdown/parser/grammar.rb +56 -0
  63. data/lib/coridoc/markdown/parser/grammar_runtime.rb +164 -0
  64. data/lib/coridoc/markdown/parser/html_entities.rb +2149 -0
  65. data/lib/coridoc/markdown/parser/inline_parser.rb +296 -0
  66. data/lib/coridoc/markdown/parser/parsanol_atoms.rb +36 -0
  67. data/lib/coridoc/markdown/parser.rb +11 -0
  68. data/lib/coridoc/markdown/parser_util.rb +90 -0
  69. data/lib/coridoc/markdown/schema/definition.rb +81 -0
  70. data/lib/coridoc/markdown/schema/loader.rb +68 -0
  71. data/lib/coridoc/markdown/schema/parity.rb +101 -0
  72. data/lib/coridoc/markdown/schema.rb +53 -0
  73. data/lib/coridoc/markdown/serializer/builder.rb +57 -0
  74. data/lib/coridoc/markdown/serializer/config.rb +71 -0
  75. data/lib/coridoc/markdown/serializer/context.rb +66 -0
  76. data/lib/coridoc/markdown/serializer/element_serializer.rb +46 -0
  77. data/lib/coridoc/markdown/serializer/flavor.rb +82 -0
  78. data/lib/coridoc/markdown/serializer/registrations.rb +113 -0
  79. data/lib/coridoc/markdown/serializer/registry.rb +62 -0
  80. data/lib/coridoc/markdown/serializer/runner.rb +84 -0
  81. data/lib/coridoc/markdown/serializer/serializers/abbreviation.rb +19 -0
  82. data/lib/coridoc/markdown/serializer/serializers/admonition.rb +20 -0
  83. data/lib/coridoc/markdown/serializer/serializers/attribute_list.rb +25 -0
  84. data/lib/coridoc/markdown/serializer/serializers/blockquote.rb +19 -0
  85. data/lib/coridoc/markdown/serializer/serializers/code.rb +19 -0
  86. data/lib/coridoc/markdown/serializer/serializers/code_block.rb +19 -0
  87. data/lib/coridoc/markdown/serializer/serializers/comment.rb +31 -0
  88. data/lib/coridoc/markdown/serializer/serializers/cross_reference.rb +19 -0
  89. data/lib/coridoc/markdown/serializer/serializers/definition_list.rb +20 -0
  90. data/lib/coridoc/markdown/serializer/serializers/document.rb +22 -0
  91. data/lib/coridoc/markdown/serializer/serializers/emphasis.rb +19 -0
  92. data/lib/coridoc/markdown/serializer/serializers/example_block.rb +48 -0
  93. data/lib/coridoc/markdown/serializer/serializers/extension.rb +30 -0
  94. data/lib/coridoc/markdown/serializer/serializers/footnote.rb +20 -0
  95. data/lib/coridoc/markdown/serializer/serializers/footnote_reference.rb +19 -0
  96. data/lib/coridoc/markdown/serializer/serializers/hard_line_break.rb +22 -0
  97. data/lib/coridoc/markdown/serializer/serializers/heading.rb +19 -0
  98. data/lib/coridoc/markdown/serializer/serializers/highlight.rb +19 -0
  99. data/lib/coridoc/markdown/serializer/serializers/horizontal_rule.rb +19 -0
  100. data/lib/coridoc/markdown/serializer/serializers/image.rb +19 -0
  101. data/lib/coridoc/markdown/serializer/serializers/link.rb +29 -0
  102. data/lib/coridoc/markdown/serializer/serializers/list.rb +43 -0
  103. data/lib/coridoc/markdown/serializer/serializers/literal.rb +26 -0
  104. data/lib/coridoc/markdown/serializer/serializers/math.rb +23 -0
  105. data/lib/coridoc/markdown/serializer/serializers/open_block.rb +38 -0
  106. data/lib/coridoc/markdown/serializer/serializers/paragraph.rb +23 -0
  107. data/lib/coridoc/markdown/serializer/serializers/pass.rb +30 -0
  108. data/lib/coridoc/markdown/serializer/serializers/sidebar.rb +33 -0
  109. data/lib/coridoc/markdown/serializer/serializers/strikethrough.rb +19 -0
  110. data/lib/coridoc/markdown/serializer/serializers/strong.rb +19 -0
  111. data/lib/coridoc/markdown/serializer/serializers/subscript.rb +19 -0
  112. data/lib/coridoc/markdown/serializer/serializers/superscript.rb +19 -0
  113. data/lib/coridoc/markdown/serializer/serializers/table.rb +37 -0
  114. data/lib/coridoc/markdown/serializer/serializers/text.rb +19 -0
  115. data/lib/coridoc/markdown/serializer/serializers/underline.rb +19 -0
  116. data/lib/coridoc/markdown/serializer/serializers/verse.rb +31 -0
  117. data/lib/coridoc/markdown/serializer/strategies/admonition/base.rb +41 -0
  118. data/lib/coridoc/markdown/serializer/strategies/admonition/container.rb +34 -0
  119. data/lib/coridoc/markdown/serializer/strategies/admonition/gfm_alert.rb +28 -0
  120. data/lib/coridoc/markdown/serializer/strategies/admonition/github.rb +27 -0
  121. data/lib/coridoc/markdown/serializer/strategies/admonition/html.rb +25 -0
  122. data/lib/coridoc/markdown/serializer/strategies/admonition/registry.rb +50 -0
  123. data/lib/coridoc/markdown/serializer/strategies/autolink/angle.rb +35 -0
  124. data/lib/coridoc/markdown/serializer/strategies/autolink/bare.rb +23 -0
  125. data/lib/coridoc/markdown/serializer/strategies/autolink/base.rb +33 -0
  126. data/lib/coridoc/markdown/serializer/strategies/autolink/none.rb +27 -0
  127. data/lib/coridoc/markdown/serializer/strategies/autolink/registry.rb +58 -0
  128. data/lib/coridoc/markdown/serializer/strategies/definition_list/base.rb +37 -0
  129. data/lib/coridoc/markdown/serializer/strategies/definition_list/flat.rb +64 -0
  130. data/lib/coridoc/markdown/serializer/strategies/definition_list/nested_html.rb +54 -0
  131. data/lib/coridoc/markdown/serializer/strategies/definition_list/registry.rb +37 -0
  132. data/lib/coridoc/markdown/serializer.rb +48 -0
  133. data/lib/coridoc/markdown/toc_generator.rb +209 -0
  134. data/lib/coridoc/markdown/transform/block_transformer.rb +163 -0
  135. data/lib/coridoc/markdown/transform/from_core_model.rb +613 -0
  136. data/lib/coridoc/markdown/transform/image_transformer.rb +21 -0
  137. data/lib/coridoc/markdown/transform/inline_transformer.rb +78 -0
  138. data/lib/coridoc/markdown/transform/list_transformer.rb +58 -0
  139. data/lib/coridoc/markdown/transform/structural_transformer.rb +94 -0
  140. data/lib/coridoc/markdown/transform/table_transformer.rb +40 -0
  141. data/lib/coridoc/markdown/transform/text_extraction.rb +19 -0
  142. data/lib/coridoc/markdown/transform/to_core_model.rb +304 -0
  143. data/lib/coridoc/markdown/transformer.rb +48 -0
  144. data/lib/coridoc/markdown/version.rb +7 -0
  145. data/lib/coridoc/markdown.rb +218 -0
  146. data/schemas/blocks.yml +73 -0
  147. data/schemas/document.yml +55 -0
  148. data/schemas/inline.yml +57 -0
  149. data/schemas/lists.yml +35 -0
  150. data/schemas/tables.yml +11 -0
  151. metadata +279 -0
@@ -0,0 +1,296 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ module Markdown
5
+ module Parser
6
+ # Load-time DSL side effect (sanctioned require_relative exception)
7
+ require_relative 'parsanol_atoms'
8
+
9
+ autoload :HtmlEntities, "#{__dir__}/html_entities"
10
+
11
+ class InlineParser < Parsanol::Parser
12
+ rule(:line_ending) { (str("\n") | str("\r\n") | str("\r")).ignore }
13
+ rule(:line_ending_or_eof) { line_ending | any.absent? }
14
+ rule(:whitespace) { match[" \t"] }
15
+ rule(:unicode_whitespace) { match["\\p{Zs}\t\r\n\f"] | any.absent? }
16
+ rule(:unicode_punctuation) { match['\\p{P}\\p{S}'] }
17
+
18
+ def unicode_codepoint(base, s)
19
+ i = s.to_s.to_i(base)
20
+ return "\uFFFD" if i.zero?
21
+
22
+ i.chr(Encoding::UTF_8)
23
+ rescue RangeError
24
+ "\uFFFD"
25
+ end
26
+
27
+ def unicode_dec(s)
28
+ unicode_codepoint(10, s)
29
+ end
30
+
31
+ def unicode_hex(s)
32
+ unicode_codepoint(16, s)
33
+ end
34
+
35
+ def lookup_entity(s)
36
+ HTML_ENTITIES[s.to_s] || "&#{s};"
37
+ end
38
+
39
+ def process_code(s)
40
+ s = s.to_s
41
+ s.tr!("\n", ' ')
42
+ return s.slice(1, s.length - 2) if s.length > 2 && s.start_with?(' ') && s.end_with?(' ')
43
+
44
+ s
45
+ end
46
+
47
+ rule(:escape) { str('\\').ignore >> match["!\"#$%&'\\(\\)*+,\\-./:;<=>?@\\[\\\\\\]\\^_`\\{\\|\\}~"] }
48
+ rule(:dec_entity) do
49
+ str('&#').ignore >> match['0-9'].repeat(1, 7).as(:dec_entity) >> str(';').ignore
50
+ end
51
+ rule(:hex_entity) do
52
+ str('&#').ignore >> match['xX'].ignore >> match['A-Fa-f0-9'].repeat(1, 6).as(:hex_entity) >> str(';').ignore
53
+ end
54
+ rule(:entity) do
55
+ str('&').ignore >> match['A-Za-z0-9'].repeat(1).as(:entity_name) >> str(';').ignore
56
+ end
57
+ rule(:nul_byte) { str("\0").output("\uFFFD") }
58
+ rule(:special_char) { escape | dec_entity | hex_entity | entity | nul_byte }
59
+
60
+ rule(:text) do
61
+ (special_char | (element.absent? >> any)).repeat(1).as(:text)
62
+ end
63
+
64
+ rule(:code_span) do
65
+ Parsanol::Atoms::Lookbehind.new(1, '`', positive: false) >>
66
+ str('`').repeat(1).capture(:code_opener).ignore >>
67
+ dynamic do |_src, ctx|
68
+ ending = (Parsanol::Atoms::Lookbehind.new(1, '`', positive: false) >> str(ctx.captures[:code_opener]).ignore >> str('`').absent?)
69
+ (ending.absent? >> any).repeat(1).as(:code_raw) >> ending
70
+ end
71
+ end
72
+
73
+ rule(:delimiter_run) do
74
+ str('*').repeat(1) | str('_').repeat(1)
75
+ end
76
+
77
+ rule(:both_flanking_delimiter_run) do
78
+ Parsanol::Atoms::Lookbehind.regex('[\\s\\S]') >>
79
+ Parsanol::Atoms::Lookbehind.regex('[\\p{Zs}\\t\\r\\n\\f]', positive: false) >> (
80
+ (
81
+ Parsanol::Atoms::Lookbehind.regex('[\\p{P}\\p{S}]') >>
82
+ delimiter_run.as(:bfdr) >>
83
+ unicode_punctuation.present?
84
+ ) | (
85
+ Parsanol::Atoms::Lookbehind.regex('[\\p{P}\\p{S}]', positive: false) >>
86
+ delimiter_run.as(:bfdr) >>
87
+ unicode_punctuation.absent?
88
+ )
89
+ ) >> unicode_whitespace.absent?
90
+ end
91
+
92
+ rule(:left_flanking_delimiter_run) do
93
+ (
94
+ (
95
+ delimiter_run.as(:lfdr) >>
96
+ unicode_punctuation.absent?
97
+ ) | (
98
+ (Parsanol::Atoms::Lookbehind.regex('[\\p{Zs}\\t\\r\\n\\f\\p{P}\\p{S}]') | Parsanol::Atoms::Lookbehind.regex('[\\s\\S]', positive: false)) >>
99
+ delimiter_run.as(:lfdr)
100
+ )
101
+ ) >> unicode_whitespace.absent?
102
+ end
103
+
104
+ rule(:right_flanking_delimiter_run) do
105
+ Parsanol::Atoms::Lookbehind.regex('[\\s\\S]') >>
106
+ Parsanol::Atoms::Lookbehind.regex('[\\p{Zs}\\t\\r\\n\\f]', positive: false) >> (
107
+ (
108
+ Parsanol::Atoms::Lookbehind.regex('[\\p{P}\\p{S}]') >>
109
+ delimiter_run.as(:rfdr) >>
110
+ (unicode_whitespace | unicode_punctuation).present?
111
+ ) | (
112
+ Parsanol::Atoms::Lookbehind.regex('[\\p{P}\\p{S}]', positive: false) >>
113
+ delimiter_run.as(:rfdr)
114
+ )
115
+ )
116
+ end
117
+
118
+ rule(:non_flanking_delimiter_run) do
119
+ left_flanking_delimiter_run.absent? >> left_flanking_delimiter_run.absent? >> delimiter_run.as(:nfdr)
120
+ end
121
+
122
+ rule(:flanking_delimiter_run) do
123
+ both_flanking_delimiter_run | left_flanking_delimiter_run | right_flanking_delimiter_run | non_flanking_delimiter_run
124
+ end
125
+
126
+ rule(:run_surrounded_by_punctuation) do
127
+ (Parsanol::Atoms::Lookbehind.regex('[\\p{P}\\p{S}]') >> flanking_delimiter_run >> unicode_punctuation.present?).as(:rsp)
128
+ end
129
+
130
+ rule(:run_preceded_by_punctuation) do
131
+ (Parsanol::Atoms::Lookbehind.regex('[\\p{P}\\p{S}]') >> flanking_delimiter_run).as(:rpp)
132
+ end
133
+
134
+ rule(:run_followed_by_punctuation) do
135
+ (flanking_delimiter_run >> unicode_punctuation.present?).as(:rfp)
136
+ end
137
+
138
+ rule(:checked_delimiter_run) do
139
+ run_surrounded_by_punctuation | run_preceded_by_punctuation | run_followed_by_punctuation | flanking_delimiter_run
140
+ end
141
+
142
+ rule(:element) { code_span | checked_delimiter_run }
143
+
144
+ rule(:inline) { (text | element).repeat }
145
+
146
+ root :inline
147
+
148
+ def can_open_emphasis(elem)
149
+ return false unless elem[:left_flanking]
150
+ return true unless elem[:char] == '_'
151
+
152
+ !elem[:right_flanking] || (elem[:right_flanking] && elem[:preceded_by_punc])
153
+ end
154
+
155
+ def can_close_emphasis(elem)
156
+ return false unless elem[:right_flanking]
157
+ return true unless elem[:char] == '_'
158
+
159
+ !elem[:left_flanking] || (elem[:left_flanking] && elem[:followed_by_punc])
160
+ end
161
+
162
+ def rule_of_three(opener, closer)
163
+ return true unless (can_open_emphasis(opener) && can_close_emphasis(opener)) ||
164
+ (can_open_emphasis(closer) && can_close_emphasis(closer))
165
+
166
+ ((opener[:length] % 3).zero? && (closer[:length] % 3).zero?) ||
167
+ (opener[:length] + closer[:length]) % 3 != 0
168
+ end
169
+
170
+ def used_delims_to_text(elems)
171
+ elems.map do |elem|
172
+ if elem.key?(:char)
173
+ next if elem[:length] < 1
174
+
175
+ { text: elem[:char] * elem[:length] }
176
+ else
177
+ elem
178
+ end
179
+ end.compact
180
+ end
181
+
182
+ def build_delim_stack(tree)
183
+ delim_stack = []
184
+ tree.each_with_index do |elem, idx|
185
+ next unless elem.is_a?(Hash) || elem.length != 1
186
+
187
+ key = elem.first.first
188
+ if %i[rsp rpp rfp].include?(key)
189
+ outer_key = key
190
+ tree[idx] = elem = elem[key]
191
+ key = elem.first.first
192
+ end
193
+ next unless %i[bfdr lfdr rfdr nfdr].include?(key)
194
+
195
+ delim_stack << idx
196
+ # pp elem
197
+ elem[:char] = elem[key].to_s[0]
198
+ elem[:length] = elem[key].length
199
+ elem[:left_flanking] = %i[bfdr lfdr].include?(key)
200
+ elem[:right_flanking] = %i[bfdr rfdr].include?(key)
201
+ elem[:preceded_by_punc] = %i[rsp rpp].include?(outer_key)
202
+ elem[:followed_by_punc] = %i[rsp rfp].include?(outer_key)
203
+ # elem[:active] = true
204
+ end
205
+ # pp delim_stack
206
+ delim_stack
207
+ end
208
+
209
+ def process_emphasis(tree)
210
+ delim_stack = build_delim_stack(tree)
211
+ cur_pos = 0
212
+ openers_bottom = { '*' => 0, '_' => 0 }
213
+ while (closer_offset = delim_stack[cur_pos..].index { |i| can_close_emphasis(tree[i]) })
214
+ # puts "-----"
215
+ # pp tree
216
+ # puts "clofset #{closer_offset} -> cur_pos #{closer_offset + cur_pos}"
217
+ cur_pos += closer_offset
218
+ closer = tree[closer_idx = delim_stack[cur_pos]]
219
+ # puts "closer:#{cur_pos}, #{closer}"
220
+ # look back - in reverse?
221
+ opener_bottom = openers_bottom[closer[:char]]
222
+ opener_to_cur = delim_stack.slice(opener_bottom, cur_pos - opener_bottom)
223
+ # puts "obottom #{opener_bottom} len #{cur_pos - opener_bottom} -> opener_to_cur #{opener_to_cur}"
224
+ opener_offset = (opener_to_cur || []).rindex do |i|
225
+ can_open_emphasis(tree[i]) && tree[i][:char] == closer[:char] && rule_of_three(tree[i], closer)
226
+ end
227
+ # puts "opener:#{opener_offset}"
228
+ if opener_offset
229
+ opener = tree[opener_idx = delim_stack[opener_bottom + opener_offset]]
230
+ strong = opener[:length] > 1 && closer[:length] > 1
231
+ # pp opener
232
+ contents_range = (opener_idx + 1)..(closer_idx - 1)
233
+ # puts "crange #{contents_range} size #{contents_range.size}"
234
+ contents = used_delims_to_text(tree.slice!(contents_range))
235
+ tree.insert(opener_idx + 1, { (strong ? :strong : :emph) => contents })
236
+ middle = (opener_bottom + opener_offset + 1)..(cur_pos - 1)
237
+ delim_stack.slice!(middle)
238
+ # puts "slice middle #{middle} -> #{delim_stack}"
239
+ delim_stack.map! { |i| i <= opener_idx ? i : (i - contents_range.size + 1) }
240
+ # puts "slice map <dstack.map!> #{delim_stack}"
241
+ cur_pos -= middle.size
242
+ if (opener[:length] -= strong ? 2 : 1).zero?
243
+ delim_stack.slice!(opener_bottom + opener_offset)
244
+ cur_pos -= 1
245
+ # puts "slice opener #{opener_bottom + opener_offset} -> #{delim_stack} @#{cur_pos}"
246
+ end
247
+ if (closer[:length] -= strong ? 2 : 1).zero?
248
+ delim_stack.slice!(cur_pos)
249
+ # puts "slice closer #{cur_pos} -> #{delim_stack}"
250
+ end
251
+ else
252
+ openers_bottom[closer[:chr]] = cur_pos - 1
253
+ if can_open_emphasis(closer)
254
+ cur_pos += 1
255
+ else
256
+ delim_stack.slice!(cur_pos)
257
+ # puts "nopener slice #{cur_pos} -> #{delim_stack}"
258
+ end
259
+ end
260
+ end
261
+ # puts "----------"
262
+ used_delims_to_text(tree)
263
+ # puts "----------"
264
+ # pp x
265
+ end
266
+
267
+ # Grammar-phase Ruby callables (parsanol-ruby#163: not
268
+ # wire-expressible) are replaced by raw captures, decoded here
269
+ # so parse() output is unchanged: {dec_entity: "65"} -> "A",
270
+ # {code_raw: s} -> {code: process_code(s)}.
271
+ def normalize_dynamic_captures(node)
272
+ case node
273
+ when Array
274
+ node.map { |child| normalize_dynamic_captures(child) }
275
+ when Hash
276
+ if node.size == 1
277
+ case node.keys.first
278
+ when :dec_entity then return unicode_dec(node.values.first)
279
+ when :hex_entity then return unicode_hex(node.values.first)
280
+ when :entity_name then return lookup_entity(node.values.first)
281
+ when :code_raw then return { code: process_code(node.values.first.to_s) }
282
+ end
283
+ end
284
+ node.transform_values { |v| normalize_dynamic_captures(v) }
285
+ else
286
+ node
287
+ end
288
+ end
289
+
290
+ def parse(io, options = {})
291
+ process_emphasis(normalize_dynamic_captures(super))
292
+ end
293
+ end
294
+ end
295
+ end
296
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'parsanol'
4
+
5
+ module Coridoc
6
+ module Markdown
7
+ module Parser
8
+ # DSL surface for the Markdown parser. The custom atoms this
9
+ # module once carried (Output, DynamicOutput, Lookbehind) are
10
+ # retired: fixed-yield sites use Atoms::Constant, callable
11
+ # transforms moved to the AST phase, and guards use the
12
+ # built-in Atoms::Lookbehind — the grammar is fully
13
+ # wire-expressible (parsanol-ruby#163).
14
+ module ParsanolAtoms
15
+ end
16
+ end
17
+ end
18
+ end
19
+
20
+ # Additive DSL surface (no overrides): exposes the remaining custom
21
+ # DSL on every atom. The custom DynamicOutput/Lookbehind atoms are
22
+ # GONE — raw captures decode in the AST phase and guards use the
23
+ # built-in Parsanol::Atoms::Lookbehind (literal + regex forms,
24
+ # parsanol >= 1.3.77) — parsanol-ruby#163.
25
+ module Parsanol
26
+ module Atoms
27
+ module DSL
28
+ # Matches self (discarding its captures) and yields a fixed
29
+ # value — built on Atoms::Constant so the shape is
30
+ # wire-expressible for the native engine (rs#137 follow-up).
31
+ def output(value)
32
+ ignore >> Constant.new(value)
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ module Markdown
5
+ module Parser
6
+ autoload :BlockParser, "#{__dir__}/block_parser"
7
+ autoload :InlineParser, "#{__dir__}/inline_parser"
8
+ autoload :AstProcessor, "#{__dir__}/ast_processor"
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'strscan'
4
+
5
+ module Coridoc
6
+ module Markdown
7
+ # Shared parser utilities for Markdown processing
8
+ module ParserUtil
9
+ # Parser for IAL (Inline Attribute List) syntax
10
+ #
11
+ # IAL syntax: {:.class #id key="value"}
12
+ # Supports:
13
+ # - Classes: .classname or .-classname
14
+ # - IDs: #idname
15
+ # - Key-value pairs: key="value", key='value', or key=value
16
+ #
17
+ module IalParser
18
+ # Tokenize an IAL string into its components
19
+ # @param content [String] The IAL content (without braces)
20
+ # @return [Array<Hash>] Array of tokens with :type and :value
21
+ def self.tokenize(content)
22
+ tokens = []
23
+ scanner = StringScanner.new(content.to_s)
24
+
25
+ until scanner.eos?
26
+ scanner.skip(/\s+/)
27
+ break if scanner.eos?
28
+
29
+ if scanner.scan(/\.(-?\w[\w-]*)/)
30
+ tokens << { type: :class, value: scanner[1] }
31
+ elsif scanner.scan(/#(\w[\w-]*)/)
32
+ tokens << { type: :id, value: scanner[1] }
33
+ elsif scanner.scan(/(\w[\w-]*)\s*=\s*/)
34
+ key = scanner[1]
35
+ value = extract_quoted_value(scanner, handle_escapes: true)
36
+ tokens << { type: :attribute, key: key, value: value }
37
+ elsif scanner.scan(/\S+/)
38
+ # Skip unknown tokens
39
+ end
40
+ end
41
+
42
+ tokens
43
+ end
44
+
45
+ # Parse IAL content into a hash
46
+ # @param content [String] The IAL content
47
+ # @return [Hash] Parsed result with :id, :classes, :attributes keys
48
+ def self.parse_to_hash(content)
49
+ result = { id: nil, classes: [], attributes: {} }
50
+ return result if content.nil? || content.empty?
51
+
52
+ tokens = tokenize(content)
53
+ tokens.each do |token|
54
+ case token[:type]
55
+ when :class
56
+ result[:classes] << token[:value]
57
+ when :id
58
+ result[:id] = token[:value]
59
+ when :attribute
60
+ result[:attributes][token[:key]] = token[:value]
61
+ end
62
+ end
63
+
64
+ result
65
+ end
66
+
67
+ # Extract a quoted value from the scanner
68
+ # @param scanner [StringScanner]
69
+ # @param handle_escapes [Boolean] Whether to unescape \\" and \\'
70
+ # @return [String] The extracted value
71
+ def self.extract_quoted_value(scanner, handle_escapes: false)
72
+ if scanner.scan(/"([^"\\]*(?:\\.[^"\\]*)*)"/)
73
+ value = scanner[1]
74
+ value = value.gsub('\"', '"') if handle_escapes
75
+ value
76
+ elsif scanner.scan(/'([^'\\]*(?:\\.[^'\\]*)*)'/)
77
+ value = scanner[1]
78
+ value = value.gsub('\\\'', "'") if handle_escapes
79
+ value
80
+ elsif scanner.scan(/(\S+)/)
81
+ scanner[1]
82
+ else
83
+ ''
84
+ end
85
+ end
86
+ private_class_method :extract_quoted_value
87
+ end
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ module Markdown
5
+ module Schema
6
+ # Reads schema files and builds lutaml-model schema definitions
7
+ # (Lutaml::Model::Schema::Definitions::Model) from them.
8
+ class Definition
9
+ SCALARS = %w[string integer boolean float date].freeze
10
+
11
+ # `false` is a legitimate default but lutaml-model's renderer only
12
+ # emits `default:` for truthy values; this renders as the literal.
13
+ FalseDefault = Struct.new(:source) do
14
+ def inspect = source
15
+ end
16
+
17
+ # @param files [Array<String>] schema file paths
18
+ # @return [Array<Definition>] one per declared class, in file order
19
+ def self.read(files)
20
+ files.flat_map do |file|
21
+ YAML.safe_load_file(file).fetch('classes').map do |name, spec|
22
+ new(name, spec, source: File.basename(file))
23
+ end
24
+ end
25
+ end
26
+
27
+ attr_reader :name, :source
28
+
29
+ def initialize(name, spec, source: nil)
30
+ @name = name
31
+ @spec = spec
32
+ @source = source
33
+ end
34
+
35
+ # @return [Array<String>] names of Behaviors modules to prepend
36
+ def behaviors
37
+ Array(@spec['behaviors'])
38
+ end
39
+
40
+ # @param namespace [String] namespace generated sibling classes live in
41
+ # @return [Lutaml::Model::Schema::Definitions::Model]
42
+ def to_model(namespace:)
43
+ defs = Lutaml::Model::Schema::Definitions
44
+ members = @spec.fetch('attributes').map do |attr_name, opts|
45
+ attribute(attr_name, opts, namespace)
46
+ end
47
+ defs::Model.new(class_name: name,
48
+ xml_root: defs::XmlRoot.new(kind: :none),
49
+ members: members,
50
+ parent_class: "Coridoc::Markdown::#{@spec.fetch('parent')}")
51
+ end
52
+
53
+ private
54
+
55
+ def attribute(attr_name, opts, namespace)
56
+ Lutaml::Model::Schema::Definitions::Attribute.new(
57
+ name: attr_name.to_sym, type: type_ref(opts.fetch('type'), namespace),
58
+ xml_name: attr_name, kind: :attribute,
59
+ collection: opts['collection'] == true,
60
+ default: default_for(opts)
61
+ )
62
+ end
63
+
64
+ def default_for(opts)
65
+ return unless opts.key?('default')
66
+
67
+ opts['default'] == false ? FalseDefault.new('false') : opts['default']
68
+ end
69
+
70
+ def type_ref(type, namespace)
71
+ defs = Lutaml::Model::Schema::Definitions
72
+ return defs::TypeRef.new(kind: :symbol, value: type) if SCALARS.include?(type)
73
+
74
+ # Base is hand-written and shared; every other model is a sibling.
75
+ scope = type == 'Base' ? 'Coridoc::Markdown' : namespace
76
+ defs::TypeRef.new(kind: :class_ref, value: "#{scope}::#{type}")
77
+ end
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'tmpdir'
4
+ require 'fileutils'
5
+
6
+ module Coridoc
7
+ module Markdown
8
+ module Schema
9
+ # Compiles Definitions into classes with lutaml-model's schema
10
+ # pipeline and applies the hand-written behavior modules.
11
+ #
12
+ # lutaml-model's ClassLoader writes class files under
13
+ # <dir>/<nested/namespace>/ but its registry requires them from
14
+ # <dir>/<last_segment>/, so a nested namespace cannot load; this
15
+ # subclass mirrors the files to where the registry looks for them.
16
+ class Loader
17
+ DEFAULT_NAMESPACE = 'Coridoc::Markdown::Generated'
18
+
19
+ # ClassLoader with the nested-namespace path corrected.
20
+ class NestedClassLoader < Lutaml::Model::Schema::ClassLoader
21
+ def load
22
+ Dir.mktmpdir do |dir|
23
+ Lutaml::Model::Schema::FileWriter.write(@output, dir, registry_generator: @registry_generator)
24
+ mirror_class_dir(dir)
25
+ require File.join(dir, "#{registry_basename}_registry")
26
+ call_register_all
27
+ end
28
+ end
29
+
30
+ private
31
+
32
+ def mirror_class_dir(dir)
33
+ segments = @output.module_namespace.downcase.split('::')
34
+ FileUtils.cp_r(File.join(dir, *segments), File.join(dir, segments.last)) if segments.size > 1
35
+ end
36
+ end
37
+
38
+ def initialize(definitions, namespace: DEFAULT_NAMESPACE)
39
+ @definitions = definitions
40
+ @namespace = namespace
41
+ end
42
+
43
+ # @return [Array<Class>] generated classes, behaviors applied
44
+ def load
45
+ entries = @definitions.map do |definition|
46
+ Lutaml::Model::Schema::CompiledOutput::Entry.new(
47
+ definition.name, definition.to_model(namespace: @namespace), :model
48
+ )
49
+ end
50
+ output = Lutaml::Model::Schema::CompiledOutput.new(entries: entries, module_namespace: @namespace)
51
+ NestedClassLoader.load(output)
52
+ apply_behaviors
53
+ end
54
+
55
+ private
56
+
57
+ def apply_behaviors
58
+ host = Object.const_get(@namespace)
59
+ @definitions.map do |definition|
60
+ klass = host.const_get(definition.name)
61
+ definition.behaviors.each { |name| klass.prepend(Behaviors.const_get(name)) }
62
+ klass
63
+ end
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ module Markdown
5
+ module Schema
6
+ # Exhaustive IR-parity diff between two class sets, normally the
7
+ # hand-written models and the schema-generated classes.
8
+ #
9
+ # Compares, per class: presence, superclass, the ordered attribute
10
+ # list and, per attribute, its type, collection flag and default.
11
+ # Returns human-readable difference strings; empty means parity.
12
+ class Parity
13
+ # Differences accepted on purpose, each a defect of the hand-written
14
+ # models rather than of the schema.
15
+ #
16
+ # Base declares `attribute :attributes, NamedValue`, and NamedValue
17
+ # < Base, so NamedValue is autoloaded while Base is half-defined: the
18
+ # hand-written NamedValue ends up WITHOUT the inherited `attributes`
19
+ # attribute (when Heading loads first), or the require raises NameError
20
+ # (when NamedValue loads first). The generated NamedValue always has it.
21
+ KNOWN_DIFFERENCES = ['NamedValue.attributes: unexpected'].freeze
22
+
23
+ # @param expected [Module] namespace holding the reference classes
24
+ # @param actual [Module] namespace holding the classes under test
25
+ # @param names [Array<String>] class names to compare
26
+ # @param except [Array<String>] differences to ignore
27
+ def self.diff(expected:, actual:, names:, except: KNOWN_DIFFERENCES)
28
+ new(expected, actual).diff(names) - except
29
+ end
30
+
31
+ def initialize(expected, actual)
32
+ @expected = expected
33
+ @actual = actual
34
+ end
35
+
36
+ def diff(names)
37
+ names.flat_map { |name| class_diff(name) }
38
+ end
39
+
40
+ private
41
+
42
+ def class_diff(name)
43
+ want = lookup(@expected, name)
44
+ got = lookup(@actual, name)
45
+ return ["#{name}: missing from #{@expected}"] unless want
46
+ return ["#{name}: missing from #{@actual}"] unless got
47
+
48
+ superclass_diff(name, want, got) + attributes_diff(name, want, got)
49
+ end
50
+
51
+ def lookup(namespace, name)
52
+ namespace.const_get(name, false)
53
+ rescue NameError
54
+ nil
55
+ end
56
+
57
+ def superclass_diff(name, want, got)
58
+ return [] if short(want.superclass) == short(got.superclass)
59
+
60
+ ["#{name}: superclass #{short(want.superclass)} != #{short(got.superclass)}"]
61
+ end
62
+
63
+ def attributes_diff(name, want, got)
64
+ wa = want.attributes
65
+ ga = got.attributes
66
+ diffs = []
67
+ diffs << "#{name}: attribute order #{wa.keys} != #{ga.keys}" if wa.keys != ga.keys && wa.keys.sort == ga.keys.sort
68
+ (wa.keys - ga.keys).each { |a| diffs << "#{name}.#{a}: missing" }
69
+ (ga.keys - wa.keys).each { |a| diffs << "#{name}.#{a}: unexpected" }
70
+ (wa.keys & ga.keys).each { |a| diffs.concat(attribute_diff("#{name}.#{a}", wa[a], ga[a])) }
71
+ diffs
72
+ end
73
+
74
+ def attribute_diff(label, want, got)
75
+ facets = facets_of(want)
76
+ other = facets_of(got)
77
+ facets.filter_map do |facet, value|
78
+ "#{label}: #{facet} #{value.inspect} != #{other[facet].inspect}" unless value == other[facet]
79
+ end
80
+ end
81
+
82
+ def facets_of(attribute)
83
+ { type: short(attribute.type), collection: attribute.collection?, default: default_of(attribute) }
84
+ end
85
+
86
+ def default_of(attribute)
87
+ register = Lutaml::Model::Config.default_register
88
+ return :none unless attribute.default_set?(register)
89
+
90
+ attribute.default(register)
91
+ end
92
+
93
+ # Class identity is compared by unqualified name so Coridoc::Markdown::X
94
+ # and Coridoc::Markdown::Generated::X are the same type.
95
+ def short(type)
96
+ type.to_s.split('::').last
97
+ end
98
+ end
99
+ end
100
+ end
101
+ end