amath 0.1.0 → 0.2.0

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.
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "lutaml/model"
4
+
5
+ module Amath
6
+ # The typed AsciiMath model Amath.parse_model returns, declared with LutaML
7
+ # Model. Its classes are generated from the normalized grammar's capture
8
+ # shapes (scripts/generate_model.rb -> lib/amath/model/nodes.rb), except
9
+ # MathSymbol and Document below. See docs/parser-contract.adoc.
10
+ module Model
11
+ # The derived +value+ and +kind+ of a class holding a catalog spelling.
12
+ module Spelled
13
+ # The portable declaration describes stored strings. Ruby keeps its
14
+ # existing live spelling readers by refreshing those typed slots on
15
+ # access, including after an in-place spelling edit. Target adapters
16
+ # resolve the same catalog before constructing their generated models.
17
+ def self.included(klass)
18
+ klass.class_eval do
19
+ def value
20
+ @value = symbol_value
21
+ end
22
+
23
+ def kind
24
+ @kind = symbol_kind
25
+ end
26
+ end
27
+ end
28
+
29
+ def symbol_value
30
+ spelling && Symbols.lookup(spelling).value
31
+ end
32
+
33
+ def symbol_kind
34
+ spelling && Symbols.lookup(spelling).kind
35
+ end
36
+ end
37
+
38
+ # A catalog symbol: the text of a catalog capture (rule N9 puts it
39
+ # under +spelling+), with the Unicode +value+ and +kind+ ("symbol",
40
+ # "open", "close", "paren" or "unlisted") the legacy symbol lookup gives
41
+ # it (Amath::Symbols). +value+ and +kind+ are derived from +spelling+.
42
+ class MathSymbol < Lutaml::Model::Serializable
43
+ attribute :spelling, :string
44
+ attribute :value, :string
45
+ attribute :kind, :string
46
+ include Spelled
47
+
48
+ end
49
+ end
50
+ end
51
+
52
+ require_relative "model/nodes"
53
+
54
+ module Amath
55
+ module Model
56
+ # The result of one parse: the expression (nil for empty input) and
57
+ # the decimal marker it was parsed with. Numbers keep their source
58
+ # text, so "1,5" under decimal: "," is the number text "1,5".
59
+ class Document < Lutaml::Model::Serializable
60
+ attribute :expression, "Amath::Model::Expression"
61
+ attribute :decimal, :string
62
+
63
+ end
64
+
65
+ # The result of one pma parse (Amath.parse_model(input, dialect: :pma)): the
66
+ # one term pma version 1 reads. Its measured values are the same
67
+ # Uncertainty (and Unit) classes dialect L builds.
68
+ class PmaDocument < Lutaml::Model::Serializable
69
+ attribute :term, "Amath::Model::Term"
70
+
71
+ end
72
+
73
+ # Every model class, in name order.
74
+ def self.classes
75
+ constants.sort.map { |c| const_get(c) }
76
+ .select { |k| k.is_a?(Class) && k < Lutaml::Model::Serializable }
77
+ end
78
+ end
79
+ end
data/lib/amath/parser.rb CHANGED
@@ -1,18 +1,54 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Amath
4
- # Checks the arguments of Amath.parse, picks the artifact entry for the
5
- # decimal marker and hands the input to the engine.
4
+ # Checks the arguments of Amath.parse and Amath.parse_model, picks the artifact entry for the
5
+ # decimal marker, hands the input to the engine and builds the model.
6
6
  module Parser
7
7
  module_function
8
8
 
9
+ # The typed model (Amath::Model::Document) of +input+: the artifact's
10
+ # declared binding (`root -> expression (any)`) gives the tree as plain
11
+ # data, and lutaml-model builds the nested model from the declared
12
+ # attribute types. Empty input is a Document without expression.
13
+ def model(input, decimal:, engine:)
14
+ entry, text, tree = run(input, decimal: decimal, engine: engine)
15
+ return Model::Document.new(decimal: decimal) if text.empty?
16
+
17
+ bound = Amath.bindings.apply(entry, tree)
18
+ Model::Document.new(expression: bound.fetch(:expression), decimal: decimal)
19
+ end
20
+
21
+ # The legacy-shaped raw tree of +input+ (Hash/Array of Parsanol::Slice
22
+ # leaves, or a plain "" for empty input), as amath 0.1 returned it; what
23
+ # Amath.parse returns. See RawTree.
24
+ def raw(input, decimal: ".", engine: :auto)
25
+ RawTree.legacy(run(input, decimal: decimal, engine: engine).last)
26
+ end
27
+
28
+ # amath 0.1's Parser.parse: the raw tree, with the same required keywords.
9
29
  def parse(input, decimal:, engine:)
30
+ raw(input, decimal: decimal, engine: engine)
31
+ end
32
+
33
+ # [entry, input text, tree of the normalized grammar].
34
+ def run(input, decimal:, engine:)
10
35
  entry = entry_for(decimal)
11
36
  text = normalize_input(input)
12
37
  mode = Engine.resolve(engine)
13
38
  tree = Engine.run(Amath.artifact, entry, text, mode,
14
39
  fallback: engine == :auto)
15
- Renester.call(tree)
40
+ [entry, text, tree]
41
+ end
42
+
43
+ # The bundled grammar's entry rules put the whole expression under one
44
+ # `root` capture, the capture its declared bindings read. The tree
45
+ # Amath returns is the expression itself, as before that capture
46
+ # existed. An artifact without the capture (test fixtures) is returned
47
+ # unchanged.
48
+ def unwrap_root(tree)
49
+ return tree unless tree.instance_of?(Hash) && tree.size == 1 && tree.key?(:root)
50
+
51
+ tree[:root]
16
52
  end
17
53
 
18
54
  def entry_for(decimal)
data/lib/amath/pma.rb ADDED
@@ -0,0 +1,285 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "json"
5
+
6
+ module Amath
7
+ # pma (dialect P, "plurimath ascii"), selected with
8
+ # Amath.parse_model(input, dialect: :pma); specified by plurimath
9
+ # docs/pma.adoc. It parses with its own artifact (artifacts/pma.json) and
10
+ # never falls back to dialect L. The content of unit(...) is parsed by the
11
+ # asciiunits artifact, the one whose checksum artifacts/pma.checksums.txt
12
+ # records.
13
+ #
14
+ # Every refusal is an Amath::ParseError whose #category names the rule
15
+ # the input breaks (Refusal::CATEGORIES); version 1 refuses every form
16
+ # the specification leaves open.
17
+ module Pma
18
+ ENTRY = "document"
19
+ ARTIFACT_PATH = File.expand_path("../../artifacts/pma.json", __dir__)
20
+ CHECKSUMS_PATH = File.expand_path("../../artifacts/pma.checksums.txt", __dir__)
21
+ UNITS_ENTRY = "expression"
22
+ QUANTITIES_PATH = File.expand_path("../../data/quantities.json", __dir__)
23
+
24
+ @artifact = Artifact.new(ARTIFACT_PATH, entries: [ENTRY])
25
+ @units = nil
26
+ @units_lock = Mutex.new
27
+ @quantities = nil
28
+ @quantities_lock = Mutex.new
29
+
30
+ module_function
31
+
32
+ def artifact
33
+ @artifact
34
+ end
35
+
36
+ # The typed model (Amath::Model::PmaDocument) of +input+.
37
+ def parse(input, decimal:, engine:)
38
+ unless decimal == "."
39
+ raise ArgumentError,
40
+ "dialect: :pma has no decimal: option in version 1 " \
41
+ "(got #{decimal.inspect}); numbers use the full stop"
42
+ end
43
+
44
+ text = Parser.normalize_input(input)
45
+ mode = Engine.resolve(engine)
46
+ tree = begin
47
+ Engine.run(@artifact.fetch, ENTRY, text, mode, fallback: engine == :auto)
48
+ rescue NestingTooDeep
49
+ raise
50
+ rescue ParseError => e
51
+ raise Refusal.error(text, e.byte_offset, Refusal.category(text))
52
+ end
53
+ check_units(tree, text, mode)
54
+ bound = @artifact.bindings.apply(ENTRY, tree)
55
+ document = Model::PmaDocument.new(term: bound.fetch(:term))
56
+ resolve_quantities(document.term)
57
+ document
58
+ end
59
+
60
+ # The unitsdb quantities a quantity assertion may name: English name
61
+ # => unitsml id (data/quantities.json, written by scripts/quantities.rb).
62
+ def quantities
63
+ @quantities_lock.synchronize { @quantities ||= load_quantities }
64
+ end
65
+
66
+ def load_quantities
67
+ doc = JSON.parse(File.read(QUANTITIES_PATH))
68
+ map = doc.fetch("quantities")
69
+ unless doc.fetch("sha256") == "sha256:#{Digest::SHA256.hexdigest(JSON.generate(map))}"
70
+ raise ArtifactError, "#{QUANTITIES_PATH} does not match its recorded sha256"
71
+ end
72
+
73
+ map
74
+ rescue SystemCallError, JSON::ParserError, KeyError => e
75
+ raise ArtifactError, "quantities cannot be loaded: #{e.class}: #{e.message}"
76
+ end
77
+
78
+ # The asciiunits artifact, checked against the checksum recorded when
79
+ # the pma artifact was compiled.
80
+ def units_artifact
81
+ @units_lock.synchronize { @units ||= load_units }
82
+ end
83
+
84
+ def load_units
85
+ require "asciiunits"
86
+ expected = File.foreach(CHECKSUMS_PATH).find { |l| l.start_with?("asciiunits_artifact_checksum ") }
87
+ raise ArtifactError, "#{CHECKSUMS_PATH} records no asciiunits artifact" unless expected
88
+
89
+ expected = expected.split[1]
90
+ actual = JSON.parse(File.read(Asciiunits::ARTIFACT_PATH)).fetch("checksum")
91
+ unless actual == expected
92
+ raise ArtifactError,
93
+ "asciiunits artifact #{Asciiunits::ARTIFACT_PATH} has checksum #{actual}, " \
94
+ "the pma artifact was composed with #{expected}"
95
+ end
96
+
97
+ Asciiunits.load_artifact
98
+ rescue LoadError, SystemCallError, JSON::ParserError, KeyError, Parsanol::PARG::Error => e
99
+ raise ArtifactError, "asciiunits artifact cannot be loaded: #{e.class}: #{e.message}"
100
+ end
101
+
102
+ # Every unit(...) text of +tree+ must be a non-empty asciiunits unit
103
+ # expression (the grammar keeps `::` out of it), and a quantity
104
+ # assertion after it must name a unitsdb quantity; an unknown name is
105
+ # refused as a quantity assertion, at the name.
106
+ def check_units(tree, text, mode)
107
+ units_in(tree).each do |unit|
108
+ slice = unit[:literal] || unit[:empty_list]
109
+ start = byte_start(text, slice)
110
+ raise Refusal.error(text, start, "unit-expression") unless unit[:literal]
111
+
112
+ begin
113
+ units_artifact.parse(UNITS_ENTRY, slice.to_s, mode: mode)
114
+ rescue Parsanol::ParseFailed => e
115
+ inner = ErrorPosition.byte_offset(e, units_artifact, UNITS_ENTRY, slice.to_s)
116
+ raise Refusal.error(text, inner && (start + inner), "unit-expression")
117
+ end
118
+ next unless unit[:quantity]
119
+
120
+ name = unit[:quantity]
121
+ raise Refusal.error(text, byte_start(text, name), "quantity-assertion") unless quantities.key?(name.to_s)
122
+ end
123
+ end
124
+
125
+ # Replaces the quantity name of every Unit of +term+ by the unitsml id
126
+ # it resolves to (check_units has refused unknown names).
127
+ def resolve_quantities(term)
128
+ [term.unit, term.uncertainty&.unit, term.diff&.uncertainty&.unit].compact.each do |unit|
129
+ unit.quantity = quantities.fetch(unit.quantity) if unit.quantity
130
+ end
131
+ end
132
+
133
+ # Every `unit` capture of a raw tree ({literal:} or {empty_list:}).
134
+ def units_in(node, out = [])
135
+ case node
136
+ when Hash
137
+ node.each do |key, value|
138
+ if key == :unit && value.is_a?(Hash)
139
+ out << value
140
+ else
141
+ units_in(value, out)
142
+ end
143
+ end
144
+ when Array then node.each { |v| units_in(v, out) }
145
+ end
146
+ out
147
+ end
148
+
149
+ # Byte offset of +slice+ in +text+ (Parsanol slice offsets count
150
+ # characters).
151
+ def byte_start(text, slice)
152
+ text[0, slice.offset].bytesize
153
+ end
154
+
155
+ private_class_method :load_units, :load_quantities, :resolve_quantities, :units_in, :byte_start
156
+
157
+ # The category of a refused pma input, from plurimath docs/pma.adoc
158
+ # "Strict error taxonomy" (plus `no-production` for text that starts
159
+ # no production at all). The first matching rule names it; the
160
+ # position is the parser's.
161
+ module Refusal
162
+ CATEGORIES = %w[
163
+ reserved-word adjacency constructor-arity constructor-argument
164
+ measured-literal plus-minus-spelling shared-exponent relative
165
+ distribution-tag concise unit-expression unit-attachment
166
+ quantity-assertion no-production
167
+ ].freeze
168
+
169
+ CONSTRUCTORS = %w[ustd uexp ucov].freeze
170
+ ARITY = { "ustd" => [2], "uexp" => [3, 4], "ucov" => [4, 5] }.freeze
171
+ CALL_WORDS = /(?<![A-Za-z])(?:unit|ustd|uexp|ucov|diff)/
172
+ WS = "[ \\t\\n\\r\\v\\f]"
173
+
174
+ module_function
175
+
176
+ def error(text, byte, category)
177
+ char = byte && ErrorPosition.char_offset(text, byte)
178
+ where = byte ? " at character #{char} (byte #{byte})" : ""
179
+ ParseError.new("pma input rejected#{where}: #{category}",
180
+ input: text, byte_offset: byte, char_offset: char, category: category)
181
+ end
182
+
183
+ def category(text)
184
+ return "reserved-word" if text.match?(/(?<![A-Za-z])quantity(?![A-Za-z])/)
185
+ return "quantity-assertion" if text.include?("::")
186
+ return "concise" if text.match?(/\d\(#{WS}*\d/o)
187
+
188
+ bare = mask_units(text)
189
+ rules(bare).each { |name, test| return name if test.call }
190
+ "no-production"
191
+ end
192
+
193
+ def rules(bare)
194
+ [
195
+ ["plus-minus-spelling", -> { bare.match?(/\+-|±|(?<![A-Za-z])pm(?![A-Za-z])/) }],
196
+ ["adjacency", -> { adjacency?(bare) }],
197
+ ["reserved-word", -> { bare.match?(/#{CALL_WORDS}(?![A-Za-z(])/o) }],
198
+ ["distribution-tag", -> { bare.include?("~") }],
199
+ ["unit-attachment", -> { attachment?(bare) }],
200
+ ["no-production", -> { bare.match?(/\A#{WS}*diff\(/o) && !bare.include?("unit(") }],
201
+ ["shared-exponent", -> { bare.match?(/\)#{WS}*e/o) }],
202
+ ["constructor-arity", -> { constructor(bare) == :arity }],
203
+ ["constructor-argument", -> { constructor(bare) == :argument }],
204
+ ["shared-exponent", -> { bare.match?(/\d[eE]/) }],
205
+ ["relative", -> { bare.include?("%") }],
206
+ ["measured-literal", -> { bare.include?("+/-") }],
207
+ ["unit-expression", -> { bare.include?("unit(") }],
208
+ ]
209
+ end
210
+
211
+ def adjacency?(bare)
212
+ bare.match?(/#{CALL_WORDS}#{WS}+\(/o) ||
213
+ bare.match?(/\)#{WS}+e[+-]?\d/o) ||
214
+ bare.match?(%r{\+#{WS}+/|/#{WS}+-}o)
215
+ end
216
+
217
+ # Two units, a unit inside a constructor call, or a unit after a
218
+ # plain number.
219
+ def attachment?(bare)
220
+ units = bare.scan("unit(").size
221
+ return true if units > 1
222
+ return false if units.zero?
223
+
224
+ call = constructor_call(bare)
225
+ return true if call && call[:args].any? { |a| a.include?("unit(") }
226
+
227
+ before = bare[0, bare.index("unit(")].rstrip
228
+ before.match?(/\d\z/) && !before.match?(/\)e[+-]?\d+\z/)
229
+ end
230
+
231
+ # :arity or :argument for a refused constructor call at the start of
232
+ # the input (after an optional diff( ), else nil.
233
+ def constructor(bare)
234
+ call = constructor_call(bare)
235
+ return nil unless call
236
+
237
+ ARITY.fetch(call[:name]).include?(call[:args].size) ? :argument : :arity
238
+ end
239
+
240
+ def constructor_call(bare)
241
+ m = bare.match(/\A#{WS}*(?:diff\(#{WS}*)?(ustd|uexp|ucov)\(/o)
242
+ return nil unless m
243
+
244
+ { name: m[1], args: arguments(bare[m.end(0)..]) }
245
+ end
246
+
247
+ # The top-level comma-separated arguments up to the matching ")".
248
+ def arguments(rest)
249
+ args = [+""]
250
+ depth = 0
251
+ rest.each_char do |c|
252
+ break if c == ")" && depth.zero?
253
+
254
+ depth += 1 if c == "("
255
+ depth -= 1 if c == ")"
256
+ c == "," && depth.zero? ? args << +"" : args.last << c
257
+ end
258
+ args
259
+ end
260
+
261
+ # +text+ with the content of every unit(...) replaced by "u", so that
262
+ # unit names such as `pm` (picometre) match no other rule.
263
+ def mask_units(text)
264
+ out = +""
265
+ i = 0
266
+ while (j = text.index("unit(", i))
267
+ out << text[i...j] << "unit("
268
+ k = j + 5
269
+ depth = 0
270
+ while k < text.length
271
+ c = text[k]
272
+ break if c == ")" && depth.zero?
273
+
274
+ depth += 1 if c == "("
275
+ depth -= 1 if c == ")"
276
+ out << "u"
277
+ k += 1
278
+ end
279
+ i = k
280
+ end
281
+ out << text[i..]
282
+ end
283
+ end
284
+ end
285
+ end
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Amath
6
+ # The internal raw-tree boundary: the parse tree of the legacy Plurimath
7
+ # AsciiMath grammar, rebuilt from the tree of amath's normalized grammar.
8
+ #
9
+ # The grammar generator (scripts/generate_grammar.rb) normalizes capture
10
+ # shapes by only ADDING captures, listed in grammars/asciimath.wrappers.json
11
+ # as {name => kind}. RawTree.legacy removes them again and renests the
12
+ # flat expression chains (Renester), so the result is exactly the legacy
13
+ # tree. It is not public API: the stage-case generator and the parity
14
+ # specs read it; Amath.parse returns this raw tree; Amath.parse_model returns the typed model.
15
+ #
16
+ # Unwrapping replaces each wrapper by the value legacy produced there and
17
+ # re-runs Parslet's flattening algebra (Parsanol::Atoms::CanFlatten
18
+ # merge_fold / flatten_repetition) over the parts, bottom-up:
19
+ #
20
+ # hash entries are split, in order, into runs of ordinary keys (one
21
+ # hash part each) and wrapper keys (one part each, by kind):
22
+ # text -> the wrapped value (nil / [] -> "")
23
+ # empty -> "" (String)
24
+ # empty_list -> []
25
+ # list -> the list ([] -> "")
26
+ # nil -> nil
27
+ # then folded with merge_fold, as legacy folded the sequence.
28
+ # A hash of nil-kind wrappers only is nil.
29
+ # array elements are unwrapped, then flatten_repetition (named).
30
+ #
31
+ # The walk recurses once per tree level; the grammar bounds that depth
32
+ # (long sums are flat chains, see Renester).
33
+ module RawTree
34
+ extend Parsanol::Atoms::CanFlatten
35
+
36
+ WRAPPERS_PATH = File.expand_path("../../grammars/asciimath.wrappers.json", __dir__)
37
+
38
+ module_function
39
+
40
+ # The legacy tree of one +raw+ parse result (the entry rule's tree,
41
+ # with its `root` capture).
42
+ def legacy(raw, wrappers = self.wrappers)
43
+ Renester.call(unwrap(Parser.unwrap_root(raw), wrappers))
44
+ end
45
+
46
+ # {wrapper name => kind}, from grammars/asciimath.wrappers.json.
47
+ def wrappers
48
+ @wrappers ||= JSON.parse(File.read(WRAPPERS_PATH)).fetch("wrappers").freeze
49
+ end
50
+
51
+ def unwrap(value, wrappers = self.wrappers)
52
+ case value
53
+ when Hash then unwrap_hash(value, wrappers)
54
+ when Array then RawTree.send(:flatten_repetition, value.map { |v| unwrap(v, wrappers) }, true)
55
+ else value
56
+ end
57
+ end
58
+
59
+ def unwrap_hash(value, wrappers)
60
+ return value.to_h { |k, v| [k, unwrap(v, wrappers)] } if value.keys.none? { |k| wrappers.key?(k.to_s) }
61
+
62
+ parts = []
63
+ run = nil
64
+ only_nil = true
65
+ value.each do |k, v|
66
+ kind = wrappers[k.to_s]
67
+ if kind
68
+ parts << run if run
69
+ run = nil
70
+ only_nil &&= kind == "nil"
71
+ parts << part(kind, unwrap(v, wrappers))
72
+ else
73
+ only_nil = false
74
+ (run ||= {})[k] = unwrap(v, wrappers)
75
+ end
76
+ end
77
+ parts << run if run
78
+ return nil if only_nil
79
+
80
+ RawTree.send(:foldl, parts) { |l, r| RawTree.send(:merge_fold, l, r) }
81
+ end
82
+
83
+ def part(kind, value)
84
+ case kind
85
+ when "text" then value.nil? || value == [] ? +"" : value
86
+ when "empty" then +""
87
+ when "empty_list" then []
88
+ when "list" then value == [] ? +"" : value
89
+ when "nil" then nil
90
+ else raise ArgumentError, "unknown wrapper kind #{kind}"
91
+ end
92
+ end
93
+
94
+ private_class_method :unwrap_hash, :part
95
+ end
96
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Amath
6
+ # The legacy AsciiMath symbol lookup, exported once from Plurimath by
7
+ # scripts/export_symbols.rb into data/asciimath-symbols.json: for every
8
+ # spelling the legacy tables list, the Unicode value, MathML element,
9
+ # kind and Plurimath class the legacy transform resolves it to.
10
+ #
11
+ # Lookup follows Asciimath::Utility.asciimath_symbol_object: the exact
12
+ # text first; text with surrounding whitespace resolves as its stripped
13
+ # text, through the record's +padded+ resolution where the legacy tables
14
+ # resolve that differently. Text no record lists is an unlisted symbol of
15
+ # its own text.
16
+ module Symbols
17
+ DATA_PATH = File.expand_path("../../data/asciimath-symbols.json", __dir__)
18
+ Entry = Struct.new(:value, :mathml, :kind, :klass, keyword_init: true)
19
+
20
+ @lock = Mutex.new
21
+
22
+ module_function
23
+
24
+ # spelling => record, loaded once.
25
+ def catalog
26
+ @catalog || @lock.synchronize do
27
+ @catalog ||= JSON.parse(File.read(DATA_PATH, encoding: "UTF-8"))
28
+ .fetch("symbols").to_h { |r| [r.fetch("spelling"), r] }.freeze
29
+ end
30
+ end
31
+
32
+ # The Entry for +text+ (a catalog capture's spelling).
33
+ def lookup(text)
34
+ record = catalog[text]
35
+ return entry(record) if record
36
+
37
+ stripped = text.strip
38
+ record = catalog[stripped] unless stripped == text
39
+ return entry(record.fetch("padded", record)) if record
40
+
41
+ Entry.new(value: text, mathml: nil, kind: "unlisted", klass: nil)
42
+ end
43
+
44
+ def entry(record)
45
+ Entry.new(value: record.fetch("value"), mathml: record.fetch("mathml"),
46
+ kind: record.fetch("kind"), klass: record.fetch("class"))
47
+ end
48
+ end
49
+ end
data/lib/amath/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Amath
4
- VERSION = "0.1.0"
4
+ VERSION = "0.2.0"
5
5
  end
data/lib/amath.rb CHANGED
@@ -18,10 +18,15 @@ module Amath
18
18
  autoload :ErrorPosition, "amath/error_position"
19
19
  autoload :Parser, "amath/parser"
20
20
  autoload :Renester, "amath/renester"
21
+ autoload :RawTree, "amath/raw_tree"
22
+ autoload :Model, "amath/model"
23
+ autoload :Symbols, "amath/symbols"
24
+ autoload :Pma, "amath/pma"
21
25
 
22
26
  # Decimal marker => artifact entry name.
23
27
  DECIMAL_ENTRIES = Configuration::DECIMAL_ENTRIES
24
28
  ENGINES = Configuration::ENGINES
29
+ DIALECTS = Configuration::DIALECTS
25
30
  THREAD_NATIVE_DEPTH = Configuration::THREAD_NATIVE_DEPTH
26
31
  OPENING = Configuration::OPENING
27
32
  CLOSING = Configuration::CLOSING
@@ -31,17 +36,38 @@ module Amath
31
36
 
32
37
  module_function
33
38
 
34
- # Parse +input+ and return the Parsanol tree (Hash/Array of
35
- # Parsanol::Slice leaves, or a plain "" for empty input).
39
+ # Parse +input+ and return its raw tree, exactly as amath 0.1 did: a
40
+ # Hash/Array tree with Parsanol::Slice leaves (a plain "" for empty input),
41
+ # or an Amath::ParseError for rejected input. This is the released 0.1
42
+ # contract (plurimath 0.11.x depends on it through "~> 0.1") and does not
43
+ # change; the typed model is Amath.parse_model.
44
+ def parse(input, decimal: ".", engine: :auto)
45
+ Parser.raw(input, decimal: decimal, engine: engine)
46
+ end
47
+
48
+ # Parse +input+ and return its typed model (see docs/parser-contract.adoc).
49
+ #
50
+ # dialect: :legacy (the default) reads dialect L and returns an
51
+ # Amath::Model::Document; empty input is a Document whose expression is
52
+ # nil. dialect: :pma reads pma (plurimath docs/pma.adoc) with its own
53
+ # artifact and returns an Amath::Model::PmaDocument; a refusal is an
54
+ # Amath::ParseError with a #category. Any other dialect is an
55
+ # ArgumentError, raised before an artifact is loaded.
36
56
  #
37
57
  # The engine that ran is available afterwards from Amath.last_engine.
38
- def parse(input, decimal: ".", engine: :auto)
39
- Parser.parse(input, decimal: decimal, engine: engine)
58
+ def parse_model(input, dialect: :legacy, decimal: ".", engine: :auto)
59
+ case dialect
60
+ when :legacy then Parser.model(input, decimal: decimal, engine: engine)
61
+ when :pma then Pma.parse(input, decimal: decimal, engine: engine)
62
+ else
63
+ raise ArgumentError,
64
+ "unknown dialect #{dialect.inspect} (use #{DIALECTS.map(&:inspect).join(', ')})"
65
+ end
40
66
  end
41
67
 
42
68
  # The engine (:native or :ruby) that produced the result (tree or
43
- # rejection) of the last Amath.parse call on the current thread that
44
- # reached the parser; nil before any parse. Under engine: :auto this is
69
+ # rejection) of the last Amath.parse or Amath.parse_model call on the
70
+ # current thread that reached the parser; nil before any parse. Under engine: :auto this is
45
71
  # :ruby when the native engine hit its recursion limit and amath reran
46
72
  # the input on the Ruby engine.
47
73
  def last_engine
@@ -66,6 +92,11 @@ module Amath
66
92
  def artifact
67
93
  @artifact.fetch
68
94
  end
95
+
96
+ # The artifact's declared Ruby bindings, paired with #artifact.
97
+ def bindings
98
+ @artifact.bindings
99
+ end
69
100
  end
70
101
 
71
102
  # Installs a hook into Parsanol at load time, so it is required, not