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,293 @@
1
+ = Shared parser stage contract
2
+ :toc:
3
+
4
+ This profile defines the common shape of the amath, latexmath and
5
+ unicodemath stage gems. Each stage owns its grammar, input processing and
6
+ typed language model. Plurimath consumes that model through a thin mapper
7
+ into its shared Formula tree. No stage depends on Plurimath at runtime.
8
+
9
+ This is the target contract for the model-based APIs in
10
+ https://github.com/plurimath/plurimath/issues/541[the rearchitecture roadmap].
11
+ It does not claim that the current gems already implement every requirement.
12
+ In particular, amath 0.1.x returned a raw tree; amath main now returns the
13
+ typed model, a breaking change released as 0.2.0. See
14
+ link:parser-contract.adoc[the amath parser contract] for its
15
+ implementation.
16
+
17
+ == Stage contents and ownership
18
+
19
+ Each language has one set of definitions, consumed by every target:
20
+
21
+ . A PARG grammar under `grammars/`, with deterministic generation inputs
22
+ such as a template and a pinned vocabulary. The committed inputs are
23
+ sufficient to build offline. A provenance export from Plurimath records
24
+ an exact source commit; a normal build never reads a mutable Plurimath
25
+ checkout or its constants.
26
+ . A compiled parse artifact and declared binding artifacts under
27
+ `artifacts/`. The bindings carry production-to-constructor mappings for
28
+ AST construction, not language semantics or writer behavior.
29
+ . A typed language model declared through lutaml-model, with exported LML
30
+ declarations and checksums. Language transforms construct that model,
31
+ never `Plurimath::Math` classes. A generic wrapper around hashes, arrays
32
+ and slices alone does not satisfy this model contract.
33
+ . A public parser, internal preprocessing and raw-tree boundaries,
34
+ conformance replay, packaging and CI for the supported engines.
35
+ . A release with identified grammar, compiler, binding, LML and corpus
36
+ versions. Language-specific notes reference this profile rather than
37
+ defining a second copy of the common rules.
38
+
39
+ Each stage records the mapping from grammar productions to its typed fields.
40
+ The stages get that mapping by construction: each grammar generator
41
+ normalizes capture shapes with the shared rules N1-N7 of
42
+ `scripts/normalize_shapes.rb` plus its own language rules (one kind per
43
+ capture, captures only added),
44
+ and the model classes are generated from the normalized captures. amath's
45
+ use of the rules, the wrapper captures and the unwrap back to the legacy
46
+ raw tree are described in link:parser-contract.adoc#normalization[the amath
47
+ parser contract].
48
+ Plurimath separately records the stage-model-to-Formula mapping. Shared
49
+ Formula/Function/Core migration belongs to Plurimath; moving a language
50
+ transform into a stage must not copy that common class hierarchy into it.
51
+ LML declares model data. Target-specific writers remain separate from the
52
+ declarations and from binding records.
53
+
54
+ == One public parsing API
55
+
56
+ All three stage gems expose the same parsing shape:
57
+
58
+ [source,ruby]
59
+ ----
60
+ model = Stage.parse(input, decimal: ".", engine: :auto)
61
+ ----
62
+
63
+ `Stage` stands for `Amath`, `Latexmath` or `Unicodemath`. The result is the
64
+ stage's typed LML language model, including a declared representation of
65
+ empty input. It is not a raw Parsanol tree or a Plurimath Formula.
66
+
67
+ There is no parallel public `parse_model` entry point. Raw parsing is an
68
+ internal/test boundary and is not an alternative API for consumers.
69
+ Diagnostic access such as amath's `last_engine` does not provide another
70
+ parsing path. A stage documents its root model and fields, but never chooses
71
+ a different public return boundary to preserve a legacy raw-tree API.
72
+
73
+ `input` is a String. Normalize its encoding to valid UTF-8 before language
74
+ preprocessing. Non-String input, invalid UTF-8 and strings that cannot be
75
+ transcoded raise `ArgumentError`. Do not coerce numbers or other objects
76
+ into source text.
77
+
78
+ `decimal:` explicitly selects the decimal marker. Dot (`"."`), comma
79
+ (`","`) and Arabic decimal separator (`"٫"`, U+066B) have declared grammar
80
+ entries; unsupported values raise `ArgumentError`. There is no implicit
81
+ locale lookup or cross-call mutable decimal setting. Preserve exact decimal
82
+ source text in model data; a float conversion must not alter the contract.
83
+
84
+ === Engines
85
+
86
+ `engine:` accepts `:auto`, `:ruby` and `:native`; any other value raises
87
+ `ArgumentError`.
88
+
89
+ [cols="1,3"]
90
+ |===
91
+ |Selection |Required behavior
92
+
93
+ |`:ruby`
94
+ |Use the Ruby engine only.
95
+
96
+ |`:native`
97
+ |Use the native engine or raise `Stage::EngineUnavailable`. Do not silently
98
+ use Ruby. A native depth limit raises `Stage::NestingTooDeep`.
99
+
100
+ |`:auto`
101
+ |Use native where available, otherwise Ruby. A native recursion or stack
102
+ limit may retry with Ruby. The result still obeys the same typed-model and
103
+ corpus contract.
104
+ |===
105
+
106
+ Record the engine that produced the result or parse rejection in a
107
+ thread-local diagnostic, with `nil` before any parser run. Under automatic
108
+ depth fallback it identifies Ruby. It must not imply that an untested
109
+ platform or every native internal operation has been verified.
110
+
111
+ Engine choice cannot change accepted input, typed field values or declared
112
+ writer outcomes. Parser engines (Ruby/native) and XML engines
113
+ (Ox/Oga/Leptris) are different test axes. Slow-engine measurements do not
114
+ justify silently dropping required parity cases.
115
+
116
+ == Preprocessing and internal raw trees
117
+
118
+ The public parser owns all language preprocessing and postprocessing needed
119
+ to interpret the caller's text. Callers do not reproduce entity encoding,
120
+ whitespace treatment, label handling, row-break restoration or text-command
121
+ protection. A language that needs none, as amath currently does, documents
122
+ that fact in its language notes.
123
+
124
+ Keep the caller's normalized UTF-8 string separately from the grammar input.
125
+ If preprocessing changes text length or encoding, retain a source mapping
126
+ back to that caller string for public error positions. Do not expose
127
+ entity-encoded offsets as if they were offsets into the original text.
128
+
129
+ The internal/test boundary exposes the preprocessed text and raw grammar
130
+ tree for parity capture. Preserve node/key kinds, array order, absent versus
131
+ nil fields, slice text and raw byte offsets. Raw offsets refer to the exact
132
+ grammar input; public error offsets refer to the normalized caller input.
133
+ The raw-tree representation is not the public model and consumers do not
134
+ depend on its leaf classes.
135
+
136
+ Replay records the caller input/options, preprocessed input, raw tree and
137
+ typed model separately. The facade mapper must also reproduce the fixed
138
+ Formula/writer outcomes. A raw-tree match alone is not processing parity.
139
+
140
+ == Errors and positions
141
+
142
+ Each stage has its own namespace with this common error shape:
143
+
144
+ `Stage::Error < StandardError`::
145
+ Base for deliberately raised stage errors, except invalid arguments.
146
+
147
+ `Stage::ParseError < Stage::Error`::
148
+ The input is refused for the selected language/options. Full consumption is
149
+ required; a valid prefix is not a successful partial parse. Expose `input`
150
+ (normalized UTF-8 caller input), `byte_offset` (zero-based UTF-8 bytes) and
151
+ `char_offset` (zero-based characters). Map positions through preprocessing.
152
+ Human-readable message wording is not a parity contract; refusal categories
153
+ and positioned outcomes are pinned by the corpus.
154
+
155
+ `Stage::NestingTooDeep < Stage::ParseError`::
156
+ The selected execution path cannot handle the input's depth. Offsets are
157
+ `nil` when no rejection position is known, and `input` is set. This does not
158
+ claim that the input is grammatically invalid. A Ruby stack exhaustion must
159
+ not escape as an unclassified `SystemStackError`.
160
+
161
+ `Stage::ArtifactError < Stage::Error`::
162
+ A required parse, binding or model artifact is missing, malformed,
163
+ unsupported, fails verification or does not match its paired artifacts.
164
+ Never fall back to a different grammar or unchecked artifact.
165
+
166
+ `Stage::EngineUnavailable < Stage::Error`::
167
+ The caller explicitly selected an unavailable native engine.
168
+
169
+ `ArgumentError`::
170
+ Invalid input type/encoding, unsupported decimal marker or engine option.
171
+
172
+ Character offsets count characters in the normalized UTF-8 string, not
173
+ grapheme clusters. Multibyte input must have tests that distinguish byte
174
+ offsets from character offsets. Internal grammar diagnostics may use other
175
+ coordinates; the stage converts them before raising a public parse error.
176
+
177
+ == Compilation and verification
178
+
179
+ Use amath's existing regeneration shape: generate/check the grammar, compile
180
+ the parse artifact, verify it against the source, and prove deterministic
181
+ output. amath's compile script compiles with `--bindings all`, which emits one
182
+ binding artifact per target with Parsanol 1.3.131 or later (earlier releases
183
+ accept the flag and emit nothing), and verifies each emitted file.
184
+
185
+ Stages adopting this profile declare the construction bindings and use that
186
+ existing compiler step to emit the target artifacts. Consumers verify each
187
+ binding artifact's kind, checksum, target and binding version, and pair its
188
+ grammar identity/source hash with the parse artifact. Test tampering, wrong
189
+ targets and wrong pairings. Do not introduce a separate handwritten target
190
+ mapping that bypasses the declarations.
191
+
192
+ Record the compiler, artifact edition and per-file checksums. Extend the
193
+ manifest to cover emitted binding and LML artifacts as they are adopted;
194
+ the parse-artifact checksum alone does not verify them. Verify exported
195
+ LML declarations and their checksums too. A Ruby re-export comparison is
196
+ not evidence of independent Rust or TS materialization. Unsupported model
197
+ declarations must fail explicitly rather than disappear from the export.
198
+
199
+ == Corpus pins and replay
200
+
201
+ The authoritative corpus contract is
202
+ https://github.com/plurimath/plurimath-testsuite/blob/6f8bc12602e6016290179f0939b6afd518ef44df/docs/stage-corpus-contract.adoc[stage
203
+ layout revision 1], together with its
204
+ https://github.com/plurimath/plurimath-testsuite/blob/6f8bc12602e6016290179f0939b6afd518ef44df/docs/tree-parity-contract.adoc[tree
205
+ parity contract]. Their schemas and validator own the wire format; this
206
+ profile does not redefine it.
207
+
208
+ Data is stored at
209
+ `stages/<language>/generations/<NNNNNN>/{provenance.yaml,payloads/<group>.yaml}`
210
+ with an append-only `generations/<language>.yaml` ledger. Use `asciimath`,
211
+ `latex` and `unicode` for these three gems. `roundtrip` is the shared
212
+ cross-language lane. A new language key, including `pma`, requires a layout
213
+ revision; it cannot be introduced by a stage data PR.
214
+
215
+ A consumer commits `spec/fixtures/testsuite-pin.yml`, for example:
216
+
217
+ [source,yaml]
218
+ ----
219
+ schema: plurimath-stage/pin/1
220
+ repository: https://github.com/plurimath/plurimath-testsuite
221
+ commit: 6f8bc12602e6016290179f0939b6afd518ef44df
222
+ language: asciimath
223
+ generation: 1
224
+ snapshot_digest: sha256:f33825074cc075f906aa96467f80b83ebbbd1729d3696d0f5613157ca0e14fa7
225
+ ----
226
+
227
+ This is a valid layout example, not a claim that the copied facade rows
228
+ already cover the new typed stage model. Stage adoption adds the missing
229
+ raw/typed expectations and source provenance in a later generation.
230
+
231
+ Before replay, run from an environment with the pinned testsuite checkout:
232
+
233
+ [source,sh]
234
+ ----
235
+ ruby "$TESTSUITE_CHECKOUT/scripts/validate-stages.rb" "$TESTSUITE_CHECKOUT" --pin spec/fixtures/testsuite-pin.yml
236
+ ----
237
+
238
+ The validator checks the checkout commit, named generation (not the latest
239
+ one), snapshot digest, payload integrity and nonempty inventory. The stage
240
+ then replays every selected row, asserting the boundary each row declares:
241
+ internal raw tree, typed model, refusal or facade/writer outcome through the
242
+ appropriate integration adapter. A stage must not silently ignore existing
243
+ facade rows that need an adapter. CI reports complete case counts and fails
244
+ missing, duplicate or unhandled cases.
245
+
246
+ A testsuite commit can advance without changing this language's generation.
247
+ Upgrading the generation deliberately updates its commit/generation/digest
248
+ with a reason.
249
+ Published generations and earlier expected outcomes never change. Stage
250
+ expectations may add producers beside the legacy oracle; they never replace
251
+ that oracle to make parity pass. Keep per-payload provenance, exact source
252
+ and dependency identities, and tracked upstream import checksums.
253
+
254
+ == CI and packaging
255
+
256
+ CI verifies deterministic grammar/artifacts, binding and LML pairings,
257
+ standalone model construction without Plurimath, and the pinned generation
258
+ on supported Ruby/native paths. Include negative artifact tests, multibyte
259
+ positions, malformed input, empty input, depth behavior and unavailable
260
+ native selection. A facade integration lane checks the Formula mapper and
261
+ unchanged writer bytes. New targets replay the same generations as they
262
+ arrive, with cross-runtime byte comparison; a Ruby-only declaration check
263
+ does not substitute for those tests.
264
+
265
+ Build and install the gem in isolation and smoke-test `parse` returning the
266
+ typed model. Package the grammar/model artifacts and runtime data needed to
267
+ load offline. Release and regeneration paths consume the committed inputs
268
+ and verify their identities. Full suites run in CI; targeted local checks
269
+ do not constitute full-suite evidence.
270
+
271
+ == Versioning and publication order
272
+
273
+ Breaking changes are allowed and carry an explicit version and migration
274
+ contract. The gems need not share version numbers. The latexmath rebuild
275
+ replaces its old 0.1.x public API as 1.0.0. UnicodeMath's first version is
276
+ chosen at its release. Amath changes `parse` from raw tree to typed LML
277
+ model in 0.2.0, not as an additive second parser API or a 0.1.x patch.
278
+
279
+ Before amath 0.2.0 is published, publish a Plurimath release that either:
280
+
281
+ * pins the old boundary with `amath ~> 0.1.0`; or
282
+ * already consumes the typed-model API and declares compatible dependencies.
283
+
284
+ Plurimath 0.11.13 through 0.11.17 use `amath ~> 0.1`, which permits 0.2.x.
285
+ A source-only pin change, unpublished PR, green CI or release-ready packet
286
+ does not satisfy this release-order gate. New Plurimath consumers install
287
+ the published stage versions and replay their fixed corpus generations.
288
+
289
+ Prepare the verified version, source commit, package/artifact checksums and
290
+ CI receipts before requesting publication. Trusted publishing is configured
291
+ and verified through the release process, not inferred from a workflow
292
+ file's presence. This documentation does not dispatch a release or implement
293
+ the amath API migration.
@@ -0,0 +1,20 @@
1
+ {
2
+ "format": "amath-wrappers/1",
3
+ "wrappers": {
4
+ "empty": "empty",
5
+ "empty_list": "empty_list",
6
+ "list": "list",
7
+ "literal": "text",
8
+ "literal_2": "text",
9
+ "spelling": "text"
10
+ },
11
+ "rules": {
12
+ "N1 text alternative": 22,
13
+ "N2 empty alternative": 27,
14
+ "N3 list in node slot": 6,
15
+ "N5 text sibling": 12,
16
+ "N6 forced rule": 23,
17
+ "N8 empty run": 8,
18
+ "N9 catalog spelling": 3466
19
+ }
20
+ }
@@ -6,13 +6,14 @@ module Amath
6
6
  # The compiled grammar artifact Amath parses with: loaded and verified
7
7
  # once per path, and reloaded after the path changes.
8
8
  class Artifact
9
- # Loads the Parsanol::PARG::Artifact at +path+ and checks it has an
10
- # entry for every decimal marker. Every load failure is an ArtifactError.
11
- def self.load(path)
9
+ # Loads the Parsanol::PARG::Artifact at +path+ and checks it has every
10
+ # entry of +entries+ (by default one per decimal marker). Every load
11
+ # failure is an ArtifactError.
12
+ def self.load(path, entries = Configuration::DECIMAL_ENTRIES.values)
12
13
  raise ArtifactError, "artifact not found: #{path}" unless File.file?(path)
13
14
 
14
15
  artifact = Parsanol::PARG::Artifact.load(path)
15
- missing = Configuration::DECIMAL_ENTRIES.values - artifact.entries
16
+ missing = entries - artifact.entries
16
17
  unless missing.empty?
17
18
  raise ArtifactError,
18
19
  "artifact #{path} lacks required entries: #{missing.join(', ')}"
@@ -30,9 +31,11 @@ module Amath
30
31
 
31
32
  attr_reader :path
32
33
 
33
- def initialize(path)
34
+ def initialize(path, entries: Configuration::DECIMAL_ENTRIES.values)
34
35
  @path = path
36
+ @entries = entries
35
37
  @loaded = nil
38
+ @bindings = nil
36
39
  @lock = Mutex.new
37
40
  end
38
41
 
@@ -41,12 +44,34 @@ module Amath
41
44
  @lock.synchronize do
42
45
  @path = path.to_s
43
46
  @loaded = nil
47
+ @bindings = nil
44
48
  end
45
49
  end
46
50
 
47
51
  # The Parsanol::PARG::Artifact at #path, loaded on first use.
48
52
  def fetch
49
- @lock.synchronize { @loaded ||= self.class.load(@path) }
53
+ @lock.synchronize { @loaded ||= self.class.load(@path, @entries) }
54
+ end
55
+
56
+ # The declared Ruby binding artifact beside #path, verified and paired
57
+ # with the parse artifact, loaded on first use.
58
+ def bindings
59
+ parse = fetch
60
+ @lock.synchronize { @bindings ||= self.class.load_bindings(@path, parse) }
61
+ end
62
+
63
+ def self.bindings_path(path)
64
+ path.to_s.sub(/\.json\z/, ".bindings.ruby.json")
65
+ end
66
+
67
+ def self.load_bindings(path, parse)
68
+ file = bindings_path(path)
69
+ raise ArtifactError, "binding artifact not found: #{file}" unless File.file?(file)
70
+
71
+ Parsanol::PARG::Bindings::Artifact.from_json(File.read(file), target: "ruby")
72
+ .pair_with!(parse)
73
+ rescue Parsanol::PARG::Error, JSON::ParserError, SystemCallError => e
74
+ raise ArtifactError, "binding artifact #{file} is invalid: #{e.class}: #{e.message}"
50
75
  end
51
76
  end
52
77
  end
@@ -13,6 +13,11 @@ module Amath
13
13
 
14
14
  ENGINES = %i[auto native ruby].freeze
15
15
 
16
+ # Amath.parse_model dialect: option values. :legacy is dialect L (asciimath.org
17
+ # AsciiMath as Plurimath reads it), :pma is dialect P (plurimath
18
+ # docs/pma.adoc).
19
+ DIALECTS = %i[legacy pma].freeze
20
+
16
21
  # Deepest bracket nesting sent to the native engine off the main thread.
17
22
  THREAD_NATIVE_DEPTH = 25
18
23
  OPENING = "([{\u2112\u1455".chars.freeze
data/lib/amath/engine.rb CHANGED
@@ -115,6 +115,9 @@ module Amath
115
115
  else
116
116
  artifact.parse(entry, text, mode: mode)
117
117
  end
118
+ rescue Parsanol::RecursionLimitExceeded => e
119
+ # parsanol 1.3.134+ raises this for native deep nesting.
120
+ raise NativeRecursionLimit, e.message.lines.first.to_s.strip, cause: nil
118
121
  rescue Parsanol::ParseFailed => e
119
122
  record(mode)
120
123
  raise parse_error(e, artifact, entry, text)
data/lib/amath/errors.rb CHANGED
@@ -12,13 +12,16 @@ module Amath
12
12
  # input (Parsanol's native unit); +char_offset+ counts characters, the
13
13
  # unit Parslet used.
14
14
  class ParseError < Error
15
- attr_reader :input, :byte_offset, :char_offset
15
+ attr_reader :input, :byte_offset, :char_offset, :category
16
16
 
17
- def initialize(message, input:, byte_offset:, char_offset:)
17
+ # +category+: for a pma refusal, the rule the input breaks
18
+ # (Amath::Pma::Refusal::CATEGORIES); nil for dialect L.
19
+ def initialize(message, input:, byte_offset:, char_offset:, category: nil)
18
20
  super(message)
19
21
  @input = input
20
22
  @byte_offset = byte_offset
21
23
  @char_offset = char_offset
24
+ @category = category
22
25
  end
23
26
  end
24
27