ceradoc 3.0.1

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 (152) hide show
  1. checksums.yaml +7 -0
  2. data/.rspec +3 -0
  3. data/Rakefile +8 -0
  4. data/exe/ceradoc +24 -0
  5. data/lib/ceradoc/binding_inflater.rb +118 -0
  6. data/lib/ceradoc/ceradoc.rb +164 -0
  7. data/lib/ceradoc/cli.rb +311 -0
  8. data/lib/ceradoc/configurable.rb +530 -0
  9. data/lib/ceradoc/core_model/abstract_block.rb +11 -0
  10. data/lib/ceradoc/core_model/annotation_block.rb +57 -0
  11. data/lib/ceradoc/core_model/attribute_reference_resolver.rb +155 -0
  12. data/lib/ceradoc/core_model/base.rb +281 -0
  13. data/lib/ceradoc/core_model/bibliography.rb +41 -0
  14. data/lib/ceradoc/core_model/bibliography_entry.rb +48 -0
  15. data/lib/ceradoc/core_model/block.rb +69 -0
  16. data/lib/ceradoc/core_model/callout.rb +32 -0
  17. data/lib/ceradoc/core_model/callout_text.rb +35 -0
  18. data/lib/ceradoc/core_model/children_content.rb +72 -0
  19. data/lib/ceradoc/core_model/comment_block.rb +16 -0
  20. data/lib/ceradoc/core_model/comment_line.rb +23 -0
  21. data/lib/ceradoc/core_model/definition_item.rb +68 -0
  22. data/lib/ceradoc/core_model/definition_list.rb +28 -0
  23. data/lib/ceradoc/core_model/element_attribute.rb +14 -0
  24. data/lib/ceradoc/core_model/example_block.rb +12 -0
  25. data/lib/ceradoc/core_model/footnote.rb +92 -0
  26. data/lib/ceradoc/core_model/frontmatter/codec.rb +151 -0
  27. data/lib/ceradoc/core_model/frontmatter/field_transform.rb +75 -0
  28. data/lib/ceradoc/core_model/frontmatter/frontmatter_entry.rb +22 -0
  29. data/lib/ceradoc/core_model/frontmatter/frontmatter_value.rb +78 -0
  30. data/lib/ceradoc/core_model/frontmatter/schema_resolver.rb +57 -0
  31. data/lib/ceradoc/core_model/frontmatter/text_splitter.rb +75 -0
  32. data/lib/ceradoc/core_model/frontmatter.rb +72 -0
  33. data/lib/ceradoc/core_model/has_children.rb +23 -0
  34. data/lib/ceradoc/core_model/horizontal_rule_block.rb +16 -0
  35. data/lib/ceradoc/core_model/id_generator.rb +23 -0
  36. data/lib/ceradoc/core_model/image.rb +76 -0
  37. data/lib/ceradoc/core_model/include.rb +43 -0
  38. data/lib/ceradoc/core_model/include_level_offset.rb +71 -0
  39. data/lib/ceradoc/core_model/include_options.rb +101 -0
  40. data/lib/ceradoc/core_model/inline_content.rb +78 -0
  41. data/lib/ceradoc/core_model/inline_element.rb +209 -0
  42. data/lib/ceradoc/core_model/list_block.rb +137 -0
  43. data/lib/ceradoc/core_model/list_item.rb +129 -0
  44. data/lib/ceradoc/core_model/listing_block.rb +19 -0
  45. data/lib/ceradoc/core_model/literal_block.rb +16 -0
  46. data/lib/ceradoc/core_model/metadata.rb +71 -0
  47. data/lib/ceradoc/core_model/open_block.rb +12 -0
  48. data/lib/ceradoc/core_model/output_artifact.rb +48 -0
  49. data/lib/ceradoc/core_model/paragraph_block.rb +16 -0
  50. data/lib/ceradoc/core_model/partintro_block.rb +11 -0
  51. data/lib/ceradoc/core_model/pass_block.rb +16 -0
  52. data/lib/ceradoc/core_model/quote_block.rb +14 -0
  53. data/lib/ceradoc/core_model/raw_inline_element.rb +16 -0
  54. data/lib/ceradoc/core_model/reviewer_block.rb +12 -0
  55. data/lib/ceradoc/core_model/sidebar_block.rb +12 -0
  56. data/lib/ceradoc/core_model/source_block.rb +16 -0
  57. data/lib/ceradoc/core_model/stem_block.rb +25 -0
  58. data/lib/ceradoc/core_model/structural_element.rb +157 -0
  59. data/lib/ceradoc/core_model/table.rb +148 -0
  60. data/lib/ceradoc/core_model/term.rb +53 -0
  61. data/lib/ceradoc/core_model/text_content.rb +26 -0
  62. data/lib/ceradoc/core_model/toc.rb +99 -0
  63. data/lib/ceradoc/core_model/toc_generator.rb +151 -0
  64. data/lib/ceradoc/core_model/verse_block.rb +14 -0
  65. data/lib/ceradoc/core_model.rb +92 -0
  66. data/lib/ceradoc/dispatch.rb +96 -0
  67. data/lib/ceradoc/errors.rb +387 -0
  68. data/lib/ceradoc/format_catalog.rb +102 -0
  69. data/lib/ceradoc/format_module.rb +78 -0
  70. data/lib/ceradoc/hooks.rb +176 -0
  71. data/lib/ceradoc/include_resolver/filesystem.rb +84 -0
  72. data/lib/ceradoc/include_resolver.rb +67 -0
  73. data/lib/ceradoc/include_selectors/indent.rb +54 -0
  74. data/lib/ceradoc/include_selectors/level_offset.rb +84 -0
  75. data/lib/ceradoc/include_selectors/lines.rb +60 -0
  76. data/lib/ceradoc/include_selectors/tags.rb +136 -0
  77. data/lib/ceradoc/include_selectors.rb +26 -0
  78. data/lib/ceradoc/introspection/element_counter.rb +48 -0
  79. data/lib/ceradoc/introspection.rb +72 -0
  80. data/lib/ceradoc/link_rewriter/identity.rb +13 -0
  81. data/lib/ceradoc/link_rewriter/visitor.rb +148 -0
  82. data/lib/ceradoc/link_rewriter.rb +37 -0
  83. data/lib/ceradoc/lint/registry.rb +33 -0
  84. data/lib/ceradoc/lint/rule.rb +41 -0
  85. data/lib/ceradoc/lint/runner.rb +67 -0
  86. data/lib/ceradoc/lint/template.rb +190 -0
  87. data/lib/ceradoc/lint/violation.rb +16 -0
  88. data/lib/ceradoc/lint.rb +44 -0
  89. data/lib/ceradoc/logger.rb +54 -0
  90. data/lib/ceradoc/metanorma/block_builder.rb +130 -0
  91. data/lib/ceradoc/metanorma/builder.rb +397 -0
  92. data/lib/ceradoc/metanorma/iso_builder.rb +67 -0
  93. data/lib/ceradoc/metanorma.rb +7 -0
  94. data/lib/ceradoc/performance_regression.rb +121 -0
  95. data/lib/ceradoc/pipeline.rb +169 -0
  96. data/lib/ceradoc/query.rb +486 -0
  97. data/lib/ceradoc/reference/address/anchor.rb +48 -0
  98. data/lib/ceradoc/reference/address/doi.rb +40 -0
  99. data/lib/ceradoc/reference/address/isbn.rb +39 -0
  100. data/lib/ceradoc/reference/address/path.rb +66 -0
  101. data/lib/ceradoc/reference/address/scoped_path.rb +47 -0
  102. data/lib/ceradoc/reference/address/url.rb +41 -0
  103. data/lib/ceradoc/reference/address.rb +153 -0
  104. data/lib/ceradoc/reference/catalog/composite.rb +59 -0
  105. data/lib/ceradoc/reference/catalog/local.rb +97 -0
  106. data/lib/ceradoc/reference/catalog/memory_index.rb +59 -0
  107. data/lib/ceradoc/reference/catalog.rb +33 -0
  108. data/lib/ceradoc/reference/edge/citation_options.rb +16 -0
  109. data/lib/ceradoc/reference/edge/footnote_ref_options.rb +13 -0
  110. data/lib/ceradoc/reference/edge/image_ref_options.rb +15 -0
  111. data/lib/ceradoc/reference/edge/include_options.rb +15 -0
  112. data/lib/ceradoc/reference/edge/kind.rb +72 -0
  113. data/lib/ceradoc/reference/edge/link_options.rb +12 -0
  114. data/lib/ceradoc/reference/edge/navigation_options.rb +12 -0
  115. data/lib/ceradoc/reference/edge/options.rb +13 -0
  116. data/lib/ceradoc/reference/edge.rb +80 -0
  117. data/lib/ceradoc/reference/edge_search.rb +128 -0
  118. data/lib/ceradoc/reference/materializer/base.rb +44 -0
  119. data/lib/ceradoc/reference/materializer/passthrough.rb +31 -0
  120. data/lib/ceradoc/reference/materializer/registry.rb +116 -0
  121. data/lib/ceradoc/reference/materializer.rb +14 -0
  122. data/lib/ceradoc/reference/presentation/base.rb +47 -0
  123. data/lib/ceradoc/reference/presentation/custom_hierarchy.rb +104 -0
  124. data/lib/ceradoc/reference/presentation/page.rb +20 -0
  125. data/lib/ceradoc/reference/presentation/single_document.rb +35 -0
  126. data/lib/ceradoc/reference/presentation/split_pages.rb +118 -0
  127. data/lib/ceradoc/reference/presentation.rb +16 -0
  128. data/lib/ceradoc/reference/resolution.rb +184 -0
  129. data/lib/ceradoc/reference/resolver/base.rb +15 -0
  130. data/lib/ceradoc/reference/resolver/caching.rb +37 -0
  131. data/lib/ceradoc/reference/resolver/catalog.rb +69 -0
  132. data/lib/ceradoc/reference/resolver/chain.rb +33 -0
  133. data/lib/ceradoc/reference/resolver.rb +20 -0
  134. data/lib/ceradoc/reference/result/ambiguous.rb +23 -0
  135. data/lib/ceradoc/reference/result/base.rb +46 -0
  136. data/lib/ceradoc/reference/result/missing.rb +14 -0
  137. data/lib/ceradoc/reference/result/resolved.rb +22 -0
  138. data/lib/ceradoc/reference/result.rb +20 -0
  139. data/lib/ceradoc/reference.rb +65 -0
  140. data/lib/ceradoc/registry.rb +156 -0
  141. data/lib/ceradoc/relative_path.rb +32 -0
  142. data/lib/ceradoc/resolve_includes.rb +202 -0
  143. data/lib/ceradoc/source_graph/file_node.rb +147 -0
  144. data/lib/ceradoc/source_graph/graph.rb +165 -0
  145. data/lib/ceradoc/source_graph/include_edges.rb +33 -0
  146. data/lib/ceradoc/source_graph/sidecar.rb +97 -0
  147. data/lib/ceradoc/source_graph.rb +36 -0
  148. data/lib/ceradoc/validation.rb +686 -0
  149. data/lib/ceradoc/version.rb +5 -0
  150. data/lib/ceradoc/visitor.rb +283 -0
  151. data/lib/ceradoc.rb +41 -0
  152. metadata +225 -0
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ceradoc
4
+ # Model-driven linting (#165).
5
+ #
6
+ # Rules live in the FORMAT gems and check the format-specific model
7
+ # tree — never raw text, never a homogenized CoreModel. Each rule
8
+ # declares its format and its check; the framework selects rules by
9
+ # format and runs them against the parsed tree a SourceGraph node
10
+ # exposes (parsing lazily, only files actually linted).
11
+ #
12
+ # require "ceradoc/asciidoc" # or any format gem you lint
13
+ # violations = Ceradoc::Lint.run("doc.adoc")
14
+ # violations.each { |v| puts "#{v.path}:#{v.line} [#{v.rule_id}] #{v.message}" }
15
+ #
16
+ # Format gems must be required (or +format:+ passed) — extension
17
+ # detection only sees registered formats, like the rest of Ceradoc.
18
+ module Lint
19
+ autoload :Violation, "#{__dir__}/lint/violation"
20
+ autoload :Rule, "#{__dir__}/lint/rule"
21
+ autoload :Template, "#{__dir__}/lint/template"
22
+ autoload :Registry, "#{__dir__}/lint/registry"
23
+ autoload :Runner, "#{__dir__}/lint/runner"
24
+
25
+ class << self
26
+ def registry
27
+ @registry ||= Registry.new
28
+ end
29
+
30
+ # Lint files (or an existing SourceGraph) with the rules
31
+ # registered for each file's format.
32
+ #
33
+ # @param sources [String, Array<String>, SourceGraph::Graph]
34
+ # @param format [Symbol, nil] force a format instead of
35
+ # detecting from the extension
36
+ # @param only [Array<Symbol>] restrict to these rule ids
37
+ # @param except [Array<Symbol>] skip these rule ids
38
+ # @return [Array<Violation>]
39
+ def run(sources, format: nil, only: nil, except: nil)
40
+ Runner.new(format: format, only: only, except: except).run(sources)
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ceradoc
4
+ class Logger
5
+ BADGE = 'Ceradoc'
6
+
7
+ COLORS = {
8
+ error: "\e[31m", # Red
9
+ info: "\e[34m", # Blue
10
+ reset: "\e[m", # Reset
11
+ success: "\e[32m", # Green
12
+ warn: "\e[33m", # Yellow
13
+ bold: "\e[1m",
14
+ unbold: "\e[22m"
15
+ }.freeze
16
+
17
+ def self.error(message)
18
+ log(message, :error)
19
+ end
20
+
21
+ def self.info(message)
22
+ log(message, :info)
23
+ end
24
+
25
+ def self.success(message)
26
+ log(message, :success)
27
+ end
28
+
29
+ def self.warn(message)
30
+ log(message, :warn)
31
+ end
32
+
33
+ def self.log(message, type)
34
+ Warning.warn format_message(message, type)
35
+ end
36
+
37
+ def self.format_message(message, type)
38
+ colorize(
39
+ "\n[#{BADGE}] #{COLORS[:bold]}#{type.upcase}#{COLORS[:unbold]}" \
40
+ ": #{message}\n",
41
+ type
42
+ )
43
+ end
44
+
45
+ def self.colorize(message, type)
46
+ io = type == :warn ? $stderr : $stdout
47
+ return message unless io.tty?
48
+
49
+ "#{COLORS[type]}#{message}#{COLORS[:reset]}"
50
+ end
51
+
52
+ private_class_method :log, :format_message, :colorize
53
+ end
54
+ end
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ceradoc
4
+ module Metanorma
5
+ class Builder
6
+ # Typed block construction, shared by source frontends and CoreModel callers.
7
+ module BlockBuilder
8
+ private
9
+
10
+ def block(parent, node, path)
11
+ case node
12
+ when CORE::StemBlock
13
+ formula_block(parent, node, path)
14
+ when CORE::QuoteBlock, CORE::ExampleBlock
15
+ container_block(parent, node, path)
16
+ when CORE::ParagraphBlock
17
+ unsupported(node, path, 'paragraph caption') if node.title
18
+ append(parent, 'p', paragraph(node, path))
19
+ when CORE::DefinitionList
20
+ definition_list_block(parent, node, path)
21
+ when CORE::ListBlock
22
+ list_block(parent, node, path)
23
+ when CORE::Table
24
+ append(parent, 'table', table(node, path))
25
+ when CORE::Image
26
+ image_block(parent, node, path)
27
+ when CORE::SourceBlock, CORE::ListingBlock
28
+ sourcecode_block(parent, node, path)
29
+ when CORE::AnnotationBlock
30
+ note_block(parent, node, path)
31
+ when CORE::Block
32
+ if node.resolve_semantic_type == :paragraph
33
+ append(parent, 'p', paragraph(node, path))
34
+ else
35
+ unsupported(node, path, "block type #{node.resolve_semantic_type}")
36
+ end
37
+ else
38
+ unsupported(node, path)
39
+ end
40
+ end
41
+
42
+ def formula_block(parent, node, path)
43
+ stem = C::TextElements::StemElement.new(stem_type: node.language)
44
+ text = node.content || Array(node.lines).join("\n")
45
+ if node.language.to_s.downcase.include?('latex')
46
+ stem.latexmath = C::TextElements::LatexmathElement.new(value: text)
47
+ elsif node.language.to_s.downcase == 'asciimath'
48
+ stem.asciimath = C::TextElements::Asciiml.new(value: text)
49
+ else
50
+ unsupported(node, path, "math language #{node.language}")
51
+ end
52
+ append(parent, 'formula', C::AncillaryBlocks::FormulaBlock.new(id: id(node, path), stem: stem))
53
+ end
54
+
55
+ def container_block(parent, node, path)
56
+ tag, klass = node.is_a?(CORE::QuoteBlock) ? ['quote', C::MultiParagraph::QuoteBlock] : ['example', C::AncillaryBlocks::ExampleBlock]
57
+ result = klass.new(id: id(node, path))
58
+ result.name = [C::Inline::NameWithIdElement.new(text: node.title)] if node.title && node.is_a?(CORE::ExampleBlock)
59
+ result.author = C::MultiParagraph::QuoteAuthorElement.new(text: node.attribution) if node.is_a?(CORE::QuoteBlock) && node.attribution
60
+ children = Array(node.children)
61
+ if children.empty? || children.all? { |c| c.is_a?(CORE::TextContent) || c.is_a?(CORE::InlineElement) }
62
+ append(result, 'p', paragraph(node, "#{path}/p", authored: false))
63
+ else
64
+ children.each_with_index { |c, i| block(result, c, "#{path}/#{i}") }
65
+ end
66
+ append(parent, tag, result)
67
+ end
68
+
69
+ def definition_list_block(parent, node, path)
70
+ list = C::Lists::DefinitionList.new(id: id(node, path))
71
+ Array(node.items).each_with_index do |item, i|
72
+ terms = Array(item.terms)
73
+ terms = [item.term] if terms.empty?
74
+ terms.each_with_index do |term, j|
75
+ dt = C::Lists::DtElement.new(content: [term], id: j.zero? ? item.id : nil)
76
+ append(list, 'dt', dt)
77
+ end
78
+ dd = C::Lists::DdElement.new
79
+ Array(item.definitions).each_with_index do |text, j|
80
+ append(dd, 'p', paragraph(CORE::ParagraphBlock.new(content: text), "#{path}/#{i}/#{j}"))
81
+ end
82
+ block(dd, item.nested, "#{path}/#{i}/nested") if item.nested
83
+ Array(item.attached_children).each_with_index { |child, j| block(dd, child, "#{path}/#{i}/attached/#{j}") }
84
+ append(list, 'dd', dd)
85
+ end
86
+ append(parent, 'dl', list)
87
+ end
88
+
89
+ def list_block(parent, node, path)
90
+ ordered = node.marker_type == 'ordered'
91
+ unsupported(node, path, "list type #{node.marker_type}") unless %w[ordered unordered].include?(node.marker_type)
92
+ list = (ordered ? C::Lists::OrderedList : C::Lists::UnorderedList).new(id: id(node, path))
93
+ list.start = node.start.to_s if ordered && node.start
94
+ Array(node.items).each_with_index do |item, i|
95
+ at = "#{path}/items/#{i}"
96
+ li = C::Lists::ListItem.new(id: id(item, at))
97
+ append(li, 'p', paragraph(item, "#{at}/p", authored: false))
98
+ block(li, item.nested_list, "#{at}/nested") if item.nested_list
99
+ append(list, 'li', li)
100
+ end
101
+ append(parent, ordered ? 'ol' : 'ul', list)
102
+ end
103
+
104
+ def image_block(parent, node, path)
105
+ unsupported(node, path, 'linked, floating or styled image') if node.link || node.float || node.role
106
+ image = C::IdElements::Image.new(source: node.src, alt: node.alt, width: node.width, height: node.height)
107
+ figure = C::AncillaryBlocks::FigureBlock.new(id: id(node, path), image: image)
108
+ figure.name = C::Inline::NameWithIdElement.new(text: node.caption || node.title) if node.caption || node.title
109
+ append(parent, 'figure', figure)
110
+ end
111
+
112
+ def sourcecode_block(parent, node, path)
113
+ unsupported(node, path, 'source callouts') unless Array(node.callouts).empty?
114
+ text = node.content || Array(node.lines).join("\n")
115
+ code = C::AncillaryBlocks::SourcecodeBlock.new(id: id(node, path), lang: node.language, content: text)
116
+ code.name = C::Inline::NameWithIdElement.new(text: node.title) if node.title
117
+ append(parent, 'sourcecode', code)
118
+ end
119
+
120
+ def note_block(parent, node, path)
121
+ unsupported(node, path, "annotation #{node.annotation_type}") unless node.annotation_type.to_s.downcase == 'note'
122
+ note = C::Blocks::NoteBlock.new(id: id(node, path))
123
+ note.name = [C::Inline::NameWithIdElement.new(text: node.title)] if node.title
124
+ append(note, 'p', paragraph(node, "#{path}/p", authored: false))
125
+ append(parent, 'note', note)
126
+ end
127
+ end
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,397 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ceradoc
4
+ module Metanorma
5
+ class UnsupportedNode < ArgumentError; end
6
+
7
+ # Constructs the SDK semantic graph directly from the shared CoreModel.
8
+ # There is deliberately no intermediate XML representation.
9
+ class Builder
10
+ C = ::Metanorma::Document::Components
11
+ S = ::Metanorma::Standoc::Document::Sections
12
+ CORE = Ceradoc::CoreModel
13
+ INLINE = {
14
+ 'bold' => ['strong', C::Inline::StrongRawElement],
15
+ 'italic' => ['em', C::Inline::EmRawElement],
16
+ 'monospace' => ['tt', C::Inline::TtElement],
17
+ 'underline' => ['underline', C::TextElements::UnderlineElement],
18
+ 'strikethrough' => ['strike', C::TextElements::StrikeElement],
19
+ 'subscript' => ['sub', C::Inline::SubElement],
20
+ 'superscript' => ['sup', C::Inline::SupElement],
21
+ 'link' => ['link', C::Inline::LinkElement],
22
+ 'xref' => ['xref', C::Inline::XrefElement]
23
+ }.freeze
24
+
25
+ require_relative 'block_builder'
26
+ include BlockBuilder
27
+
28
+ def self.build(document, root_class: ::Metanorma::Standoc::Document::Root)
29
+ builder_class(root_class).new(root_class).build(document)
30
+ end
31
+
32
+ FLAVOR_ROOT_NAME = /\AMetanorma::\w+::Document::Root\z/
33
+
34
+ # A native root is the shared SDK root, any flavor root named
35
+ # Metanorma::<Flavor>::Document::Root (ISO, IEC, generic, ...), or any
36
+ # Lutaml root that declares bibdata and sections.
37
+ def self.native_root?(root_class)
38
+ return false unless root_class.is_a?(Class)
39
+
40
+ return true if root_class <= ::Metanorma::Document::Root
41
+ return true if root_class.ancestors.any? { |k| FLAVOR_ROOT_NAME.match?(k.name.to_s) }
42
+
43
+ root_class.respond_to?(:attributes) && %i[bibdata sections].all? { |a| root_class.attributes.key?(a) }
44
+ end
45
+
46
+ # Type of the root's sections attribute, which selects the vocabulary
47
+ # (ISO sections for ISO and IEC, Standoc sections otherwise).
48
+ def self.sections_type(root_class)
49
+ root_class.attributes[:sections]&.type if root_class.respond_to?(:attributes)
50
+ end
51
+
52
+ def self.builder_class(root_class)
53
+ return self unless root_class.is_a?(Class)
54
+
55
+ iso = defined?(::Metanorma::Iso::Document::Sections::IsoSections) && ::Metanorma::Iso::Document::Sections::IsoSections
56
+ iso_root = defined?(::Metanorma::Iso::Document::Root) && root_class <= ::Metanorma::Iso::Document::Root
57
+ return self unless iso_root || (iso && sections_type(root_class) == iso)
58
+
59
+ require_relative 'iso_builder'
60
+ IsoBuilder
61
+ end
62
+
63
+ def self.parse(source, format: :asciidoc, **)
64
+ frontend = case format.to_sym
65
+ when :asciidoc, :adoc
66
+ require 'ceradoc/asciidoc'
67
+ Ceradoc::AsciiDoc
68
+ when :markdown
69
+ require 'ceradoc/markdown'
70
+ Ceradoc::Markdown
71
+ else
72
+ raise ArgumentError, "Unsupported source format: #{format}"
73
+ end
74
+ parsed = frontend.parse(source)
75
+ core = if format.to_sym == :markdown
76
+ require 'ceradoc/markdown/metanorma_input'
77
+ Ceradoc::Markdown::MetanormaInput.transform(parsed)
78
+ else
79
+ require 'ceradoc/asciidoc/metanorma_input'
80
+ Ceradoc::AsciiDoc::MetanormaInput.transform(parsed)
81
+ end
82
+ if parsed.frontmatter && !parsed.frontmatter.strip.empty?
83
+ frontmatter = Array(core.children).grep(CORE::FrontmatterBlock).first
84
+ raise UnsupportedNode, 'Empty or malformed source frontmatter at document/frontmatter' if !frontmatter || (Array(frontmatter.entries).empty? && frontmatter.schema.nil?)
85
+ end
86
+ if format.to_sym == :markdown
87
+ children = Array(core.children)
88
+ title_index = children.index { |node| !node.is_a?(CORE::FrontmatterBlock) }
89
+ first = title_index && children[title_index]
90
+ if first.is_a?(CORE::SectionElement) && first.level == 1 && first.title == core.title
91
+ core.id ||= first.id
92
+ core.children = children.each_with_index.filter_map { |node, i| node unless i == title_index }
93
+ end
94
+ end
95
+ build(core, **)
96
+ end
97
+
98
+ def initialize(root_class)
99
+ @root_class = root_class
100
+ end
101
+
102
+ def build(document)
103
+ @ids = {}
104
+ @sequence = Hash.new(0)
105
+ @generated = {}
106
+ raise ArgumentError, 'Expected CoreModel::DocumentElement' unless document.is_a?(CORE::DocumentElement)
107
+
108
+ raise ArgumentError, 'Expected a native SDK Root class' unless native_root_class?
109
+
110
+ unsupported(document, 'document', 'string document body; use typed children') unless document.content.to_s.empty?
111
+ reserve_ids(document, 'document')
112
+ root = @root_class.new
113
+ root.type = 'semantic' if root.respond_to?(:type=)
114
+ root.bibdata = bibliography_data(document)
115
+ sections = sections_class.new
116
+ root.sections = root_sections_collection? ? [sections] : sections
117
+ @root = root
118
+ body = Array(document.children)
119
+ # Both formats can express headings as flat siblings. Normalize them
120
+ # without changing the input graph, preserving explicitly nested sections.
121
+ populate_sections(sections, body, 'document')
122
+ root
123
+ end
124
+
125
+ private
126
+
127
+ def reserve_ids(node, path)
128
+ return unless node.is_a?(CORE::Base)
129
+
130
+ unsupported(node, path, 'element attributes') unless Array(node.element_attributes).empty?
131
+ unsupported(node, path, 'metadata entries') unless Array(node.metadata_entries).empty?
132
+ if node.is_a?(CORE::HeaderElement) && node.document_title?
133
+ unsupported(node, path, 'document title has body children') unless Array(node.children).empty?
134
+ return
135
+ end
136
+ unless node.id.to_s.empty?
137
+ raise ArgumentError, "Duplicate authored ID #{node.id.inspect} at #{path}" if @ids.key?(node.id)
138
+
139
+ @ids[node.id] = path
140
+ end
141
+ if node.is_a?(CORE::BibliographyEntry) && node.anchor_name && node.anchor_name != node.id
142
+ raise ArgumentError, "Duplicate authored ID #{node.anchor_name.inspect} at #{path}" if @ids.key?(node.anchor_name)
143
+
144
+ @ids[node.anchor_name] = path
145
+ end
146
+ node.class.attributes.each_key do |name|
147
+ next if name == :id
148
+
149
+ Array(node.public_send(name)).each_with_index do |value, i|
150
+ reserve_ids(value, "#{path}/#{name}/#{i}") if value.is_a?(CORE::Base)
151
+ end
152
+ end
153
+ end
154
+
155
+ def id(node, path)
156
+ return node.id unless node.id.to_s.empty?
157
+ return @generated[path] if @generated.key?(path)
158
+
159
+ kind = node.class.name.split('::').last
160
+ @sequence[kind] += 1
161
+ candidate = "_ceradoc_#{kind.downcase}_#{@sequence[kind]}"
162
+ candidate += '_' while @ids.key?(candidate) && @ids[candidate] != path
163
+ @ids[candidate] = path
164
+ @generated[path] = candidate
165
+ end
166
+
167
+ def unsupported(node, path, detail = nil)
168
+ raise UnsupportedNode, "#{node.class} at #{path}#{": #{detail}" if detail}"
169
+ end
170
+
171
+ # Resolve the SDK's XML vocabulary to its actual declared typed attribute.
172
+ # Section/list/note classes use different Ruby names for the same XML tag.
173
+ def append(parent, tag, value)
174
+ mapping = parent.class.mappings_for(:xml)
175
+ rule = tag == '#text' ? mapping.content_mapping : mapping.elements.find { |r| r.name.to_s == tag }
176
+ raise UnsupportedNode, "#{parent.class} cannot contain #{tag}" unless rule
177
+
178
+ name = rule.to
179
+ definition = parent.class.attributes[name]
180
+ if definition.collection?
181
+ parent.public_send("#{name}=", Array(parent.public_send(name)) + [value])
182
+ else
183
+ raise UnsupportedNode, "Repeated singular #{tag} in #{parent.class}" if parent.public_send(name)
184
+
185
+ parent.public_send("#{name}=", value)
186
+ end
187
+ order = tag == '#text' ? Lutaml::Xml::Element.new('Text', 'text', node_type: :text, text_content: value.to_s) : Lutaml::Xml::Element.new('Element', tag, node_type: :element)
188
+ parent.element_order = Array(parent.element_order) + [order]
189
+ value
190
+ end
191
+
192
+ def native_root_class?
193
+ self.class.native_root?(@root_class)
194
+ end
195
+
196
+ def root_sections_collection?
197
+ @root_class.attributes[:sections]&.collection? || false
198
+ end
199
+
200
+ def sections_class
201
+ S::Sections
202
+ end
203
+
204
+ def clause_class
205
+ S::ClauseSection
206
+ end
207
+
208
+ def metadata_keys
209
+ %w[docnumber docidentifier language title copyright-year copyright-holder]
210
+ end
211
+
212
+ def document_metadata(document)
213
+ title = document.title
214
+ title ||= Array(document.children).find { |n| n.is_a?(CORE::HeaderElement) && n.document_title? }&.title
215
+ values = Array(document.attributes&.entries).to_h { |entry| [entry.key, entry.value] }
216
+ Array(document.children).grep(CORE::FrontmatterBlock).each do |frontmatter|
217
+ unsupported(frontmatter, 'document/frontmatter', 'schema-bound frontmatter') if frontmatter.schema
218
+ native = CORE::FrontmatterBlock::Codec.to_hash(frontmatter)
219
+ values = values.merge(native.transform_keys(&:to_s))
220
+ end
221
+ unknown = values.keys - metadata_keys
222
+ unsupported(document, 'document/attributes', "unsupported metadata: #{unknown.join(', ')}") unless unknown.empty?
223
+ values.each do |key, value|
224
+ unsupported(document, 'document/attributes', "non-scalar #{key}") unless value.is_a?(String) || value.is_a?(Numeric)
225
+ end
226
+ [values['title']&.to_s || title, values]
227
+ end
228
+
229
+ def copyright_data(document, values)
230
+ return nil unless values['copyright-year'] || values['copyright-holder']
231
+
232
+ unsupported(document, 'document/attributes', 'copyright requires copyright-year and copyright-holder') unless values['copyright-year'] && values['copyright-holder']
233
+ relaton = ::Metanorma::Document::Relaton
234
+ organization = relaton::Organization.new(name: [relaton::LocalizedName.new(content: [values['copyright-holder'].to_s])])
235
+ owner = relaton::CopyrightOwner.new(organization: organization)
236
+ [relaton::CopyrightAssociation.new(from: relaton::DateTime.new(content: values['copyright-year'].to_s), owner: [owner])]
237
+ end
238
+
239
+ def bibliography_data(document)
240
+ title, values = document_metadata(document)
241
+ bib = C::BibData::BibliographicItem.new(id: document.id)
242
+ bib.title = [::Metanorma::Document::Relaton::TypedTitleString.new(content: [title])] if title
243
+ bib.copyright = copyright_data(document, values)
244
+ bib.docnumber = values['docnumber'].to_s if values['docnumber']
245
+ bib.language = [C::DataTypes::Iso639Code.new(value: values['language'])] if values['language']
246
+ bib.docidentifier = [::Metanorma::Document::Relaton::DocumentIdentifier.new(id: values['docidentifier'])] if values['docidentifier']
247
+ bib
248
+ end
249
+
250
+ def populate_sections(container, nodes, path)
251
+ stack = []
252
+ loose = nil
253
+ nodes.each_with_index do |node, index|
254
+ at = "#{path}/#{index}"
255
+ if node.is_a?(CORE::FrontmatterBlock)
256
+ next
257
+ elsif node.is_a?(CORE::Bibliography)
258
+ bibliography(node, at)
259
+ elsif node.is_a?(CORE::HeaderElement) && node.document_title?
260
+ next
261
+ elsif node.is_a?(CORE::SectionElement) || node.is_a?(CORE::HeaderElement)
262
+ level = node.level || 1
263
+ stack.pop while stack.any? && stack.last[0] >= level
264
+ parent = stack.last&.last || (container if container.is_a?(clause_class))
265
+ section = section_model(node, at, parent)
266
+ append(stack.empty? ? container : stack.last[1], 'clause', section)
267
+ populate_sections(section, Array(node.children), "#{at}/children")
268
+ stack << [level, section]
269
+ elsif node.is_a?(CORE::PreambleElement)
270
+ children = Array(node.children)
271
+ children = [CORE::ParagraphBlock.new(id: node.id, content: node.content)] if children.empty? && !node.content.to_s.empty?
272
+ populate_sections(container, children, "#{at}/children")
273
+ else
274
+ target = stack.last&.last
275
+ target ||= container if container.is_a?(clause_class)
276
+ unless target
277
+ loose ||= append(container, 'clause', clause_class.new(id: id(CORE::SectionElement.new, "#{path}/preamble")))
278
+ target = loose
279
+ end
280
+ block(target, node, at)
281
+ end
282
+ end
283
+ end
284
+
285
+ def section_model(node, at, parent)
286
+ section_id = node.id || CORE::IdGenerator.generate_from_title(node.title, parent_id: parent&.id)
287
+ if node.id.nil? && section_id
288
+ section_id += '_' while @ids.key?(section_id)
289
+ @ids[section_id] = at
290
+ end
291
+ section = clause_class.new(id: section_id || id(node, at))
292
+ unsupported(node, at, 'section attributes') if node.attributes && !Array(node.attributes.entries).empty?
293
+ section.title = C::Inline::TitleWithAnnotationElement.new
294
+ append(section.title, '#text', node.title || node.content || '')
295
+ section
296
+ end
297
+
298
+ def inline_content(target, node, path)
299
+ children = node.respond_to?(:children) ? Array(node.children) : []
300
+ if node.is_a?(CORE::InlineElement) && !Array(node.nested_elements).empty?
301
+ unsupported(node, path, 'ambiguous children and nested_elements') unless children.empty?
302
+ children = Array(node.nested_elements)
303
+ end
304
+ if children.empty?
305
+ text = node.respond_to?(:text) ? node.text : node.content
306
+ text ||= Array(node.lines).join("\n") if node.respond_to?(:lines) && !Array(node.lines).empty?
307
+ append(target, '#text', text.to_s) unless text.nil?
308
+ else
309
+ children.each_with_index { |child, i| inline(target, child, "#{path}/#{i}") }
310
+ end
311
+ end
312
+
313
+ def inline(parent, node, path)
314
+ case node
315
+ when CORE::Image
316
+ unsupported(node, path, 'linked or captioned inline image') if node.link || node.caption
317
+ append(parent, 'image', C::IdElements::Image.new(source: node.src, alt: node.alt, width: node.width, height: node.height))
318
+ when CORE::TextContent
319
+ append(parent, '#text', node.text.to_s)
320
+ when CORE::InlineElement
321
+ format = node.resolve_format_type
322
+ if format == 'text'
323
+ inline_content(parent, node, path)
324
+ elsif format == 'footnote'
325
+ fn = C::Inline::FnElement.new(id: id(node, path), reference: id(node, path))
326
+ append(fn, 'p', paragraph(node, "#{path}/p", authored: false))
327
+ append(parent, 'fn', fn)
328
+ elsif %w[hard_line_break line_break].include?(format)
329
+ append(parent, 'br', C::Inline::BrElement.new)
330
+ elsif format == 'stem'
331
+ unsupported(node, path, "math type #{node.stem_type}") unless [nil, 'stem', 'asciimath', 'AsciiMath', 'latexmath', 'latex', 'LaTeX'].include?(node.stem_type)
332
+ stem = C::Inline::StemInlineElement.new(stem_type: node.stem_type || 'AsciiMath')
333
+ if node.stem_type.to_s.downcase.include?('latex')
334
+ stem.latexmath = [C::TextElements::LatexmathElement.new(value: node.content)]
335
+ else
336
+ stem.asciimath = [C::Inline::AsciimathElement.new(text: node.content)]
337
+ end
338
+ append(parent, 'stem', stem)
339
+ elsif (mapping = INLINE[format])
340
+ tag, klass = mapping
341
+ element = klass.new
342
+ element.id = node.id if node.id && element.respond_to?(:id=)
343
+ unsupported(node, path, 'inline ID cannot be represented') if node.id && !element.respond_to?(:id=)
344
+ element.target = node.target if %w[link xref].include?(format)
345
+ inline_content(element, node, path)
346
+ append(parent, tag, element)
347
+ else
348
+ unsupported(node, path, "inline format #{format.inspect}")
349
+ end
350
+ else
351
+ unsupported(node, path, 'expected inline content')
352
+ end
353
+ end
354
+
355
+ def paragraph(node, path, authored: true)
356
+ p = C::Paragraphs::ParagraphBlock.new(id: authored ? id(node, path) : id(CORE::ParagraphBlock.new, path))
357
+ inline_content(p, node, path)
358
+ p
359
+ end
360
+
361
+ def bibliography(node, path)
362
+ section = S::StandardReferencesSection.new(id: id(node, path), normative: false)
363
+ section.title = C::Inline::TitleWithAnnotationElement.new(text: [node.title]) if node.title
364
+ section.references = Array(node.entries).each_with_index.map do |entry, i|
365
+ item = C::BibData::BibliographicItem.new(id: entry.anchor_name || id(entry, "#{path}/#{i}"))
366
+ item.docidentifier = [::Metanorma::Document::Relaton::DocumentIdentifier.new(id: entry.document_id)] if entry.document_id
367
+ item.formatted_ref = C::DataTypes::FormattedString.new(value: [entry.ref_text]) if entry.ref_text
368
+ unsupported(entry, path, 'bibliographic URL') if entry.url
369
+ item
370
+ end
371
+ @root.bibliography ||= S::BibliographySection.new
372
+ append(@root.bibliography, 'references', section)
373
+ end
374
+
375
+ def table(node, path)
376
+ result = C::Tables::TableBlock.new(id: id(node, path), width: node.width)
377
+ result.name = C::Inline::NameWithIdElement.new(text: node.title) if node.title
378
+ unsupported(node, path, 'table grid') if node.grid
379
+ result.colgroup = C::Tables::ColGroupElement.new(col: node.cols.map { |width| C::Tables::ColElement.new(width: width) }) unless Array(node.cols).empty?
380
+ body = C::Tables::TableBodySection.new
381
+ Array(node.rows).each_with_index do |row, i|
382
+ tr = C::Tables::TextTableRow.new(id: row.id)
383
+ Array(row.cells).each_with_index do |cell, j|
384
+ unsupported(cell, "#{path}/#{i}/#{j}", 'table cell style') if cell.style && !%w[default d].include?(cell.style)
385
+ klass = cell.header || row.header ? C::Tables::HeaderTableCell : C::Tables::TextTableCell
386
+ td = klass.new(id: cell.id, colspan: cell.colspan, rowspan: cell.rowspan, align: cell.alignment, valign: cell.vertical_alignment)
387
+ inline_content(td, cell, "#{path}/#{i}/#{j}")
388
+ append(tr, klass == C::Tables::HeaderTableCell ? 'th' : 'td', td)
389
+ end
390
+ append(body, 'tr', tr)
391
+ end
392
+ result.tbody = body
393
+ result
394
+ end
395
+ end
396
+ end
397
+ end