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,234 @@
1
+ {
2
+ "format": "amath-quantities/v1",
3
+ "unitsdb": "2.2.13",
4
+ "sha256": "sha256:c3dda1222a8ec148794fb187ab644ef978d0a2c4ea79a29df18327d6ff734801",
5
+ "quantities": {
6
+ "1st hyperpolarizability": "q:first_hyperpolarizability",
7
+ "2nd hyperpolarizability": "q:second_hyperpolarizability",
8
+ "Celsius temperature": "q:celsius_temperature",
9
+ "Fahrenheit temperature": "q:fahrenheit_temperature",
10
+ "Hamilton function": "q:hamilton_function",
11
+ "ITS-90 temperature (K)": "q:ITS-90_temperature_kelvin",
12
+ "ITS-90 temperature (°C)": "q:ITS-90_temperature_celsius",
13
+ "Lagrange function": "q:lagrange_function",
14
+ "PLTS-2000 temperature (K)": "q:PLTS-2000_temperature",
15
+ "Poisson number": "q:poisson_number",
16
+ "absorbed dose": "q:absorbed_dose",
17
+ "absorbed dose rate": "q:absorbed_dose_rate",
18
+ "acceleration": "q:acceleration",
19
+ "acceleration of free fall": "q:acceleration_of_free_fall",
20
+ "action": "q:action",
21
+ "activity referred to a radionuclide": "q:activity_referred_to_a_radionuclide",
22
+ "ambient dose equivalent": "q:ambient_dose_equivalent",
23
+ "amount concentration": "q:amount_concentration",
24
+ "amount of electricity": "q:amount_of_electricity",
25
+ "amount of heat": "q:amount_of_heat",
26
+ "amount of substance": "q:substance_amount",
27
+ "amount of substance concentration": "q:amount_concentration",
28
+ "angle": "q:plane_angle",
29
+ "angular acceleration": "q:angular_acceleration",
30
+ "angular frequency": "q:angular_frequency",
31
+ "angular impulse": "q:angular_impulse",
32
+ "angular momentum": "q:moment_of_momentum",
33
+ "angular repetency": "q:angular_wavenumber",
34
+ "angular velocity": "q:angular_velocity",
35
+ "angular wavenumber": "q:angular_wavenumber",
36
+ "apparent power": "q:apparent_power",
37
+ "area": "q:area",
38
+ "area moment of inertia": "q:area_moment_of_inertia",
39
+ "areic mass": "q:surface_density",
40
+ "attenuation coefficient": "q:attenuation_coefficient",
41
+ "bending moment of force": "q:bending_moment_of_force",
42
+ "breadth": "q:breadth",
43
+ "bulk modulus": "q:modulus_of_compression",
44
+ "capacitance": "q:capacitance",
45
+ "cartesian coordinates": "q:cartesian_coordinates",
46
+ "catalytic activity": "q:catalytic_activity",
47
+ "catalytic activity concentration": "q:catalytic_activity_concentration",
48
+ "coefficient of heat transfer": "q:coefficient_of_heat_transfer",
49
+ "compressibility": "q:compressibility",
50
+ "cubic expansion coefficient": "q:cubic_expansion_coefficient",
51
+ "current density": "q:current_density",
52
+ "curvature": "q:curvature",
53
+ "damping coefficient": "q:damping_coefficient",
54
+ "density": "q:density",
55
+ "diameter": "q:diameter",
56
+ "directional dose equivalent": "q:directional_dose_equivalent",
57
+ "displacement": "q:displacement",
58
+ "distance": "q:distance",
59
+ "dose equivalent": "q:dose_equivalent",
60
+ "duration": "q:time",
61
+ "dynamic friction factor": "q:dynamic_friction_factor",
62
+ "dynamic viscosity": "q:dynamic_viscosity",
63
+ "electric capacitance": "q:electric_capacitance",
64
+ "electric charge": "q:electric_charge",
65
+ "electric charge density": "q:electric_charge_density",
66
+ "electric conductance": "q:electric_conductance",
67
+ "electric current": "q:electric_current",
68
+ "electric current intensity": "q:electric_current_intensity",
69
+ "electric dipole moment": "q:electric_dipole_moment",
70
+ "electric displacement": "q:electric_displacement",
71
+ "electric field gradient": "q:electric_field_gradient",
72
+ "electric field strength": "q:electric_field_strength",
73
+ "electric flux density": "q:electric_flux_density",
74
+ "electric inductance": "q:electric_inductance",
75
+ "electric potential": "q:electric_potential",
76
+ "electric potential difference": "q:electric_potential_difference",
77
+ "electric quadrupole moment": "q:electric_quadrupole_moment",
78
+ "electric resistance": "q:electric_resistance",
79
+ "electromotive force": "q:electromotive_force",
80
+ "emission rate": "q:emission_rate",
81
+ "energy": "q:energy",
82
+ "energy density": "q:energy_density",
83
+ "entropy": "q:entropy",
84
+ "exposure": "q:exposure",
85
+ "exposure (x and gamma rays)": "q:exposure_x_and_gamma_rays",
86
+ "fluence": "q:fluence",
87
+ "fluence rate": "q:fluence_rate",
88
+ "fluidity": "q:fluidity",
89
+ "force": "q:force",
90
+ "frequency": "q:frequency",
91
+ "fuel economy": "q:fuel_efficiency",
92
+ "fuel efficiency": "q:fuel_efficiency",
93
+ "gravitational constant": "q:gravitational_constant",
94
+ "group speed": "q:group_velocity",
95
+ "group velocity": "q:group_velocity",
96
+ "heat": "q:amount_of_heat",
97
+ "heat capacity": "q:heat_capacity",
98
+ "heat flux density": "q:heat_flux_density",
99
+ "height": "q:height",
100
+ "hydrodynamic permeability": "q:hydrodynamic_permeability",
101
+ "illuminance": "q:illuminance",
102
+ "impulse": "q:impulse",
103
+ "index of acidity": "q:index_of_acidity",
104
+ "inductance": "q:inductance",
105
+ "information content": "q:information_content",
106
+ "information entropy": "q:information_content",
107
+ "irradiance": "q:irradiance",
108
+ "isothermal compressibility": "q:isothermal_compressibility",
109
+ "kerma": "q:kerma",
110
+ "kerma rate": "q:kerma_rate",
111
+ "kinematic viscosity": "q:kinematic_viscosity",
112
+ "kinetic energy": "q:kinetic_energy",
113
+ "length": "q:length",
114
+ "length of path": "q:length_of_path",
115
+ "level of a field quantity": "q:level_of_a_field_quantity",
116
+ "level of a power quantity": "q:level_of_a_power_quantity",
117
+ "linear density": "q:linear_density",
118
+ "linear expansion coefficient": "q:linear_expansion_coefficient",
119
+ "linear strain": "q:linear_strain",
120
+ "lineic mass": "q:linear_density",
121
+ "logarithmic decrement (field quantities using natural logarithms)": "q:logarithmic_decrement",
122
+ "logarithmic frequency range": "q:logarithmic_frequency_range",
123
+ "logarithmic ratio quantities (power-like quantities using decimal logarithms)": "q:logarithmic_ratio_quantities",
124
+ "luminance": "q:luminance",
125
+ "luminous flux": "q:luminous_flux",
126
+ "luminous intensity": "q:luminous_intensity",
127
+ "magnetic dipole moment": "q:magnetic_dipole_moment",
128
+ "magnetic field": "q:magnetic_field",
129
+ "magnetic field strength": "q:magnetic_field_strength",
130
+ "magnetic flux": "q:magnetic_flux",
131
+ "magnetic flux density": "q:magnetic_flux_density",
132
+ "magnetizability": "q:magnetizability",
133
+ "magnetomotive force (Cardelli) (-SP811)": "q:magnetomotive_force",
134
+ "mass": "q:mass",
135
+ "mass concentration": "q:mass_concentration",
136
+ "mass density": "q:density",
137
+ "mass divided by length": "q:mass_divided_by_length",
138
+ "mass flow rate": "q:mass_flow_rate",
139
+ "mass fraction": "q:mass_fraction",
140
+ "mass moment of inertia": "q:mass_moment_of_inertia",
141
+ "massic volume": "q:specific_volume",
142
+ "mechanical energy": "q:mechanical_energy",
143
+ "modulus of compression": "q:modulus_of_compression",
144
+ "modulus of elasticity": "q:modulus_of_elasticity",
145
+ "modulus of rigidity": "q:modulus_of_rigidity",
146
+ "molality of solute B": "q:molality_of_solute_B",
147
+ "molar energy": "q:molar_energy",
148
+ "molar entropy": "q:molar_entropy",
149
+ "molar heat capacity": "q:molar_heat_capacity",
150
+ "mole fraction": "q:mass_fraction",
151
+ "moment of force": "q:moment_of_force",
152
+ "moment of inertia": "q:mass_moment_of_inertia",
153
+ "moment of momentum": "q:moment_of_momentum",
154
+ "momentum": "q:momentum",
155
+ "monetary value": "q:monetary_value",
156
+ "nil": "q:nil",
157
+ "normal stress": "q:normal_stress",
158
+ "organ dose equivalent": "q:organ_dose_equivalent",
159
+ "period": "q:period_duration",
160
+ "period duration": "q:period_duration",
161
+ "permeability": "q:permeability",
162
+ "permittivity": "q:permittivity",
163
+ "personal dose equivalent": "q:personal_dose_equivalent",
164
+ "phase": "q:phase",
165
+ "phase coefficient": "q:phase_coefficient",
166
+ "phase speed": "q:phase_velocity",
167
+ "phase velocity": "q:phase_velocity",
168
+ "plane angle": "q:plane_angle",
169
+ "polarizability": "q:polarizability",
170
+ "position vector": "q:position_vector",
171
+ "potential difference": "q:potential_difference",
172
+ "potential energy": "q:potential_energy",
173
+ "power": "q:power",
174
+ "pressure": "q:pressure",
175
+ "pressure coefficient": "q:pressure_coefficient",
176
+ "propagation coefficient": "q:propagation_coefficient",
177
+ "radial distance": "q:radial_distance",
178
+ "radiance": "q:radiance",
179
+ "radiant flux": "q:radiant_flux",
180
+ "radiant intensity": "q:radiant_intensity",
181
+ "radius": "q:radius",
182
+ "radius of curvature": "q:radius_of_curvature",
183
+ "ratio logarithm (B)": "q:logarithmic_ratio_quantities",
184
+ "ratio logarithm (Np)": "q:logarithmic_decrement",
185
+ "reciprocal of dynamic viscosity": "q:fluidity",
186
+ "refractive index": "q:refractive_index",
187
+ "relative density": "q:relative_mass_density",
188
+ "relative humidity": "q:relative_humidity",
189
+ "relative mass density": "q:relative_mass_density",
190
+ "relative permeability": "q:relative_permeability",
191
+ "relative pressure coefficient": "q:relative_pressure_coefficient",
192
+ "repetency": "q:wavenumber",
193
+ "rotation": "q:rotation",
194
+ "rotational frequency": "q:rotational_frequency",
195
+ "second axial moment of area": "q:second_axial_moment_of_area",
196
+ "second moment of area": "q:area_moment_of_inertia",
197
+ "second polar moment of area": "q:second_polar_moment_of_area",
198
+ "section modulus": "q:section_modulus",
199
+ "shear modulus": "q:modulus_of_rigidity",
200
+ "shear strain": "q:shear_strain",
201
+ "shear stress": "q:shear_stress",
202
+ "solid angle": "q:solid_angle",
203
+ "specific energy": "q:specific_energy",
204
+ "specific energy imparted": "q:specific_energy_imparted",
205
+ "specific entropy": "q:specific_entropy",
206
+ "specific heat capacity": "q:specific_heat_capacity",
207
+ "specific volume": "q:specific_volume",
208
+ "speed": "q:velocity",
209
+ "speed of propagation of waves": "q:speed_of_propagation_of_waves",
210
+ "storage capacity": "q:storage_capacity",
211
+ "storage size": "q:storage_capacity",
212
+ "stress": "q:stress",
213
+ "surface charge density": "q:surface_charge_density",
214
+ "surface coefficient of heat transfer": "q:surface_coefficient_of_heat_transfer",
215
+ "surface density": "q:surface_density",
216
+ "surface tension": "q:surface_tension",
217
+ "symbol rate": "q:symbol_rate",
218
+ "thermal conductivity": "q:thermal_conductivity",
219
+ "thermodynamic temperature": "q:temperature",
220
+ "thickness": "q:thickness",
221
+ "time": "q:time",
222
+ "time constant": "q:time_constant",
223
+ "torque": "q:torque",
224
+ "traffic intensity": "q:traffic_intensity",
225
+ "velocity": "q:velocity",
226
+ "volume": "q:volume",
227
+ "volume flow rate": "q:volume_flow_rate",
228
+ "volume strain": "q:volume_strain",
229
+ "wavelength": "q:wavelength",
230
+ "wavenumber": "q:wavenumber",
231
+ "weight": "q:weight",
232
+ "work": "q:work"
233
+ }
234
+ }
@@ -1,19 +1,32 @@
1
1
  = Amath parser contract
2
2
  :toc:
3
3
 
4
- This document is the contract between amath and its callers (first of all
5
- Plurimath's AsciiMath transform). It covers the public API, decimal markers,
6
- engine policy, errors and positions. Anything not written here is not part of
7
- the contract.
4
+ The link:stage-contract.adoc[shared stage profile] defines the model-based
5
+ target for amath, latexmath and unicodemath: one public `parse` API returning
6
+ the typed LML language model, with raw parsing internal to tests and tooling.
7
+ It owns the common preprocessing, engine, error, artifact, corpus-pin and
8
+ release requirements.
8
9
 
9
- Runtime dependency: `parsanol ~> 1.3, >= 1.3.107`. amath never requires
10
- Plurimath or reads Plurimath constants.
10
+ This document describes amath's implementation of that profile. The typed
11
+ model replaces amath 0.1's raw-tree return value: it is a breaking change,
12
+ released as 0.2.0, and a published Plurimath release pinning `amath ~> 0.1.0`
13
+ or already using the typed model must come before amath 0.2.0.
14
+
15
+ AsciiMath-specific notes: input needs no language preprocessing; the decimal
16
+ entries are `dot`, `comma` and `arabic`; shared-exponent captures and exact
17
+ source-text behavior are described below.
18
+
19
+ Runtime dependencies on this main revision: `parsanol ~> 1.3, >= 1.3.131`
20
+ and `lutaml-model ~> 0.8, >= 0.8.162`. amath never requires Plurimath or
21
+ reads Plurimath constants.
11
22
 
12
23
  == API
13
24
 
14
25
  [source,ruby]
15
26
  ----
16
- Amath.parse(input, decimal: ".", engine: :auto) # => tree
27
+ Amath.parse_model(input, decimal: ".", engine: :auto) # => Amath::Model::Document
28
+ Amath.parse_model(input, dialect: :pma) # => Amath::Model::PmaDocument
29
+ Amath.parse(input, decimal: ".", engine: :auto) # => raw tree (amath 0.1 contract)
17
30
  Amath.last_engine # => :native, :ruby or nil
18
31
  Amath.native_available? # => true / false
19
32
  Amath.artifact_path # => String
@@ -30,23 +43,70 @@ position refers to that string.
30
43
 
31
44
  `engine`:: `:auto`, `:native` or `:ruby`. See <<engine>>.
32
45
 
33
- === Successful result
34
-
35
- The return value is the Parsanol tree of the selected entry:
36
-
37
- * `Hash` with Symbol keys, `Array` (order preserved), and `Parsanol::Slice`
38
- leaves;
39
- * empty input returns a plain `""` (a `String`, not a `Slice`). This is the
40
- grammar's end-of-input alternative and callers must handle it the same way
41
- they handled Parslet's empty match.
42
-
43
- The tree's key names and nesting are defined by the grammar artifact
44
- (`artifacts/asciimath.json`) and are pinned by the conformance corpus, not by
45
- this document.
46
-
47
- `Parsanol::Slice` is not `Parslet::Slice`. Callers that check the leaf class
48
- exactly (Plurimath's transform does) need an adapter; that is the caller's
49
- concern.
46
+ `dialect`:: `:legacy` (the default), dialect L, the AsciiMath this page
47
+ describes; or `:pma`, dialect P (<<pma>>). Any other value raises
48
+ `ArgumentError` before an artifact is loaded.
49
+
50
+ There is no second public parse method. The raw parse tree is internal
51
+ (<<raw-tree>>).
52
+
53
+ === Successful result: the typed model
54
+
55
+ `Amath.parse_model` returns an `Amath::Model::Document`, a LutaML Model object:
56
+
57
+ `expression`:: the expression, an `Amath::Model::Expression`; `nil` for
58
+ empty input (`""`), the declared empty representation.
59
+ `decimal`:: the decimal marker the input was parsed with.
60
+
61
+ The model classes live under `Amath::Model`. Apart from `Document` and
62
+ `MathSymbol` (`lib/amath/model.rb`) they are generated from the grammar by
63
+ `scripts/generate_model.rb` into `lib/amath/model/nodes.rb`, one class per
64
+ capture of the normalized grammar (<<normalization>>):
65
+
66
+ * a capture that holds a node is a class with one attribute per key it can
67
+ hold;
68
+ * a capture that holds a list is a collection of `<Capture>Item` elements;
69
+ * a capture that holds text is a `String` attribute, the text as written.
70
+
71
+ So an attribute has the same name and type wherever it occurs. A run of
72
+ terms (a sum, a sequence) is one `expr.amath_chain` collection of
73
+ `AmathChainItem` elements (`amath_step`, `amath_lr`, and a closing
74
+ `amath_end`), not a nesting one level per term: a 3000-term sum is a list of
75
+ 6000 items.
76
+
77
+ Numbers keep their source text, decimal marker included: under
78
+ `decimal: ","`, `1,5` is the number text `"1,5"`. There is no float
79
+ conversion anywhere in the model.
80
+
81
+ The text of a catalog capture (`symbol`, `comma`, the parens `lparen`,
82
+ `rparen`, `left`, `right`, `table_left`, `table_right`, and the `d`/`x` of a
83
+ differential) is an `Amath::Model::MathSymbol`: `spelling` is the text as
84
+ written, and `value` (the Unicode text) and `kind` (`symbol`, `open`,
85
+ `close`, `paren`, or `unlisted` for text the catalog does not list) are
86
+ derived from it through `Amath::Symbols`. The catalog is
87
+ `data/asciimath-symbols.json`, exported once by `scripts/export_symbols.rb`
88
+ from the Plurimath revision the grammar was transcribed from; it records each
89
+ spelling's Unicode value, MathML element, kind and Plurimath class, so the
90
+ Plurimath mapper can map symbols without a lookup of its own.
91
+
92
+ Uncertainty calls are `Amath::Model::Uncertainty` objects whose fields
93
+ (`uncertainty_class`, `value`, `magnitude`, `lower`, `upper`,
94
+ `concise_digits`, `shared_exponent`, `coverage_factor`,
95
+ `coverage_probability`, `interval_kind`, `unit`) are the source texts.
96
+
97
+ Wrapper attributes (`literal`, `literal_2`, `list`, `empty`, `empty_list`)
98
+ come from the shape normalization: `literal` holds text where the same slot
99
+ can also hold a node, `empty` and `empty_list` mark an optional part that
100
+ matched nothing.
101
+
102
+ `model/asciimath.lml.json` is the LML export (`Lutaml::Model::Lml.export`,
103
+ verified) of every model class; `scripts/generate_model.rb --check` in CI
104
+ requires both the classes and the export to match a fresh generation.
105
+
106
+ The model is read through its attributes. Serializing it through a
107
+ LutaML format (`to_hash`, `to_yaml`) is not supported: lutaml-model 0.8.162
108
+ compiles a serialization transformation for every path through the
109
+ recursive class graph, which does not finish for this model.
50
110
 
51
111
  === Shared exponents in uncertainty calls
52
112
 
@@ -61,11 +121,12 @@ uexp((3.85, 0.23)e+4, 2, 0.95)
61
121
  ucov((1.024, 0.983, 1.088)e-3, 0.95, shortest)
62
122
  ----
63
123
 
64
- These forms add `shared_exponent` to the existing `uncertainty` hash. Its
65
- value is the original `Parsanol::Slice` for the exponent digits and optional
66
- sign, without the `e`. All mantissas, concise digits, units and dimensionless
67
- coverage fields remain unchanged source slices with their original byte offsets.
68
- Calls without an exponent keep their existing trees.
124
+ These forms set `shared_exponent` on the `Uncertainty` model (in the raw
125
+ tree, a `shared_exponent` key in the `uncertainty` hash). Its value is the
126
+ source text of the exponent digits and optional sign, without the `e`. All
127
+ mantissas, concise digits, units and dimensionless coverage fields remain
128
+ unchanged source texts (raw-tree slices keep their byte offsets). Calls
129
+ without an exponent are unchanged.
69
130
 
70
131
  The consuming reader shifts the decimal point exactly in the value and
71
132
  magnitude, or in the value and both interval endpoints. For concise notation,
@@ -80,6 +141,16 @@ The separate expression-language forms `(3.85 +/- 0.23)e4` and `680(41)e-3`
80
141
  remain ordinary AsciiMath here; this extension uses explicit uncertainty calls.
81
142
  The input/tree and consuming-reader decimal expectations are recorded in
82
143
  `corpora/uncertainty-shared-exponent.yml`.
144
+ `scripts/generate_stage_cases.rb` turns each corpus file into a raw-tree
145
+ payload for the `asciimath` stage generations in plurimath-testsuite, after
146
+ checking that both engines return the same tree and that it carries the
147
+ corpus texts. With `--boundary typed-model` it writes `model-<group>`
148
+ payloads instead: the `Amath.parse_model` Document of each case, written from the
149
+ bound data the model is built from and typed by the declared model classes
150
+ (`model/asciimath.lml.json`), after checking that both engines agree and that
151
+ the built model gives the same rows. Its `--producer` option writes the
152
+ provenance block for that generation, including the LML export checksum for
153
+ typed-model rows.
83
154
 
84
155
  [[decimal]]
85
156
  == Decimal markers
@@ -157,11 +228,11 @@ that as `SystemStackError`.
157
228
  Length is not depth. A run of terms (a sum such as `x + x + ... + x`, a
158
229
  sequence of symbols, a comma list) is parsed as a repetition, not by one
159
230
  nested rule call per term, so neither engine gets deeper as the run gets
160
- longer. The tree is still the nested one, `{expr: term + {expr: ...}}`, one
161
- level per term: amath rebuilds it after the engine returns, without
162
- recursion (`Amath::Renester`), with the same keys, order, slices and
163
- offsets as the recursive grammar produced. Code that walks the returned
164
- tree recursively must still be ready for one level per term. When the
231
+ longer. The model keeps that run as one flat `amath_chain` list, so it is
232
+ as shallow as the input's bracket nesting, whatever the number of terms.
233
+ (The internal raw tree is the legacy nested one, `{expr: term + {expr:
234
+ ...}}`, one level per term, rebuilt without recursion by
235
+ `Amath::Renester`.) When the
165
236
  input after a run fails to parse, the grammar falls back to its recursive
166
237
  rule to find the same tree or rejection as before; such input can still
167
238
  hit the limits below.
@@ -183,14 +254,16 @@ main thread it parses 1,000 levels of `(`; rejecting deep invalid input needs
183
254
  more stack, because Parsanol reparses it with its recursive interpreter to
184
255
  find the position, so a rejection of input a few hundred levels deep can
185
256
  raise `Amath::NestingTooDeep` instead of a positioned `ParseError`. amath
186
- never lets `SystemStackError` escape from `Amath.parse`.
257
+ never lets `SystemStackError` escape from `Amath.parse` or `Amath.parse_model`.
187
258
 
188
259
  == Errors
189
260
 
190
261
  All deliberate errors inherit from `Amath::Error < StandardError`.
191
262
 
192
263
  `Amath::ParseError`::
193
- The input is not valid AsciiMath for the selected decimal marker. Full
264
+ The input is not valid AsciiMath for the selected decimal marker (or, under
265
+ `dialect: :pma`, not valid pma; then `category` names the rule it breaks,
266
+ see <<pma>>; it is nil for dialect L). Full
194
267
  consumption is required: a valid prefix followed by invalid text is a
195
268
  rejection, never a partial tree. Attributes:
196
269
  +
@@ -228,21 +301,21 @@ UTF-8.
228
301
  Parsanol reports positions in *bytes*; Parslet reported them in *characters*.
229
302
  They differ as soon as the input contains non-ASCII text.
230
303
 
231
- * `Parsanol::Slice#offset` is a zero-based byte offset. Note that
232
- `Parsanol::Slice#charpos` is an alias of `offset` and is *also* a byte
233
- offset.
304
+ * In the internal raw tree, `Parsanol::Slice#offset` is a zero-based byte
305
+ offset. Note that `Parsanol::Slice#charpos` is an alias of `offset` and is
306
+ *also* a byte offset. The model holds source texts without offsets.
234
307
  * `Amath::ParseError#byte_offset` is a byte offset and `#char_offset` is the
235
308
  character offset computed by amath.
236
309
 
237
- Example: in `text(é) x`, the leaf `x` has `offset == 9`, while it is
238
- character 8. To convert a byte offset to Parslet's character offset:
310
+ Example: in `text(é) x`, the raw-tree leaf `x` has `offset == 9`, while it
311
+ is character 8. To convert a byte offset to Parslet's character offset:
239
312
 
240
313
  [source,ruby]
241
314
  ----
242
315
  char = input.byteslice(0, byte_offset).length
243
316
  ----
244
317
 
245
- where `input` is the UTF-8 string passed to `Amath.parse`.
318
+ where `input` is the UTF-8 string passed to `Amath.parse` or `Amath.parse_model`.
246
319
 
247
320
  Known difference from Parslet: the deepest rejection position can differ by
248
321
  one. For `x 1.` the A0 spike measured Parslet's deepest failure at 3 and
@@ -255,3 +328,176 @@ gem (`Amath::DEFAULT_ARTIFACT_PATH`). It is loaded and checksum-verified once,
255
328
  on first use, and cached for the process. Assigning `Amath.artifact_path=`
256
329
  clears the cache; it exists for tests and tooling, not for selecting
257
330
  alternative grammars in production.
331
+
332
+ [[pma]]
333
+ == pma (dialect P)
334
+
335
+ `Amath.parse_model(input, dialect: :pma)` reads pma, the strict ASCII dialect
336
+ specified in plurimath `docs/pma.adoc` (amath#16). It parses with its own
337
+ artifact, `artifacts/pma.json` (grammar `grammars/pma.parg`, generated from
338
+ `grammars/pma.parg.template` and the registry's pma entries), and never with
339
+ the dialect L artifact; a refused input is never retried in the other
340
+ dialect. A missing or failing pma artifact raises `Amath::ArtifactError`.
341
+
342
+ Version 1 reads one term:
343
+
344
+ * a measured value: a measured literal `(v +/- u)`, with an optional shared
345
+ exponent `(v +/- u)e4`, a relative uncertainty `(v +/- p%)` and an optional
346
+ distribution tag inside the bracket, `(v +/- u ~rect)`; or a constructor
347
+ `ustd(v, u)`, `uexp(v, U, k[, p])`, `ucov(v, lo, hi, p[, kind])`;
348
+ * a measured value followed by `unit(...)`;
349
+ * `unit(...)` on its own;
350
+ * `diff(...)` of a measured value with its unit.
351
+
352
+ The content of `unit(...)` is unquoted and parsed by the asciiunits artifact
353
+ (gem `asciiunits`). The pma artifact's checksum record names the asciiunits
354
+ artifact the grammar was composed with, and amath refuses to run pma with
355
+ another one (`Amath::ArtifactError`).
356
+
357
+ A unit may end with a quantity assertion, `unit(J::energy)`: `::` and the
358
+ English name of a unitsdb quantity, at most one, after the whole unit
359
+ expression. The names and their unitsml identifiers are in
360
+ `data/quantities.json`, written by `scripts/quantities.rb` from the unitsdb
361
+ version the Gemfile pins. An unknown name is refused as `quantity-assertion`.
362
+ The `quantity` of the `Amath::Model::Unit` holds the identifier (`q:energy`);
363
+ amath does not check that the quantity fits the unit.
364
+
365
+ The result is an `Amath::Model::PmaDocument` whose `term` holds
366
+ `uncertainty`, `unit` or `diff`. A measured value is the same
367
+ `Amath::Model::Uncertainty` class dialect L builds, with its unit in `unit`
368
+ (an `Amath::Model::Unit` whose `literal` is the unit text). pma adds three
369
+ fields that stay nil for dialect L: `plus_minus` (`+/-` for a measured
370
+ literal, which is a standard uncertainty), `relative_magnitude` (the `p` of
371
+ `p%`) and `distribution` (`rect`, `triang` or `arcsine`). Numbers keep their
372
+ source text. `decimal:` has no meaning in pma version 1; any value other than
373
+ `"."` raises `ArgumentError`.
374
+
375
+ Every form the specification leaves open is refused. Each refusal is an
376
+ `Amath::ParseError` with `byte_offset`, `char_offset` and a `category`: one
377
+ of `reserved-word`, `adjacency`, `constructor-arity`,
378
+ `constructor-argument`, `measured-literal`, `plus-minus-spelling`,
379
+ `shared-exponent`, `relative`, `distribution-tag`, `concise`,
380
+ `unit-expression`, `unit-attachment`, `quantity-assertion` (the specification's
381
+ taxonomy) or `no-production` (text that starts no production). The position
382
+ is the parser's; for a unit the asciiunits grammar refuses, it is the
383
+ position inside the unit text. `corpora/pma/*.yml` holds every accepted and
384
+ refused example of the specification, with the categories and positions,
385
+ and is staging until the pma corpus has its place in a testsuite.
386
+
387
+ The pma grammar has no recursion: brackets inside `unit(...)` nest at most
388
+ eight deep, so deep input is a `ParseError`, never `NestingTooDeep`.
389
+
390
+ [[registry]]
391
+ == The registry
392
+
393
+ `data/vocabulary.json` is the shared registry, format `amath-vocabulary/v2`
394
+ (amath#16). Each entry has a `category` (the grammar list it belongs to), a
395
+ `value`, a `dialect` (`legacy`, `pma` or `both`) and a `binding`, which names
396
+ the parse tree leaf (capture) the entry produces and the model type of that
397
+ leaf. `scripts/generate_grammar.rb` checks that every leaf of a dialect L
398
+ binding is a capture of the dialect L grammar.
399
+
400
+ The dialect L part is pinned by edition. The entries tagged `legacy` or
401
+ `both`, written back in the v1 layout, must give exactly the bytes whose
402
+ sha256 `legacy_edition` records, and the dialect L grammar is generated from
403
+ those bytes. An entry tagged `pma` never reaches it. A new dialect L
404
+ vocabulary comes from `scripts/export_vocabulary.rb` and enters the registry
405
+ with `ruby scripts/registry.rb --import-legacy FILE`, which pins it as the
406
+ next edition and keeps the pma entries. `ruby scripts/registry.rb --check`
407
+ verifies the file and the pin.
408
+
409
+ The pma grammar is generated from the entries tagged `pma` or `both` (in
410
+ version 1, the distribution names), checked with the same shape
411
+ normalization and strict checks as dialect L, and its header records the
412
+ registry edition and the asciiunits artifact (`units` in the registry). The
413
+ model is generated from both grammars (`scripts/generate_model.rb`): a
414
+ capture name is one class with the keys of both, and every binding's model
415
+ type is checked against the generated model.
416
+
417
+ The registry also lists the pma reserved words (`unit`, `ustd`, `uexp`,
418
+ `ucov`, `diff`, `quantity`). They are grammar terminals, not entries.
419
+ `scripts/check_reserved_words.rb` fails the build when one of them is a
420
+ spelling of any registry entry, or a unit symbol or unit name in unitsdb.
421
+ CI runs both checks.
422
+
423
+ [[normalization]]
424
+ == Grammar shape normalization
425
+
426
+ `scripts/generate_grammar.rb` expands `grammars/asciimath.parg.template`
427
+ with the pinned dialect L edition of the registry `data/vocabulary.json`
428
+ (see <<registry>>), reads every rule with Parsanol's PARG parser into
429
+ a rule tree (`scripts/parg_rule_tree.rb`) and normalizes capture shapes with
430
+ the shared rules N1-N7 of `scripts/normalize_shapes.rb` (the file unicodemath
431
+ and latexmath use, from the option-F proof of concept) and amath's rules N8
432
+ and N9 with its corrections to the shared rules (`scripts/amath_shapes.rb`). Under Parslet's
433
+ flattening one capture name can hold text, a hash or a list depending on the
434
+ alternative that matched; the rules only ADD captures (which never changes
435
+ what the grammar accepts) until every capture holds one kind:
436
+
437
+ N1 text alternative:: text in a node slot becomes `(x) as literal`.
438
+ N2 empty alternative:: `[x]` in a node slot becomes `x / "" as empty`.
439
+ N3 list in node slot:: a list in a node slot becomes `(x) as list`.
440
+ N4 list slot:: a capture of a repetition stays a list of nodes.
441
+ N5 text sibling:: text beside nodes in a sequence becomes `literal`,
442
+ `literal_2`, ...
443
+ N6 forced rule:: a rule that can return text or a node is normalized once,
444
+ at every call site.
445
+ N7 presence capture:: a capture of a lookahead gets `"" as present`.
446
+ N8 empty run:: a text run that can match nothing, at a named position,
447
+ becomes `(1*(x)) as literal / "" as empty_list` (the legacy tree held `[]`).
448
+ N9 catalog spelling:: catalog text becomes `((x) as spelling) as name`.
449
+
450
+ Generation stops when a capture still holds two kinds, or only ever holds
451
+ nil, and when a rewritten rule does not read back as its normalized tree.
452
+ Besides `grammars/asciimath.parg` it writes
453
+ `grammars/asciimath.wrappers.json` (the added captures and their kinds) and
454
+ `grammars/asciimath.normalized-rules.json` (the normalized rule tree, the
455
+ input of `scripts/generate_model.rb`). A capture that holds nil only when an
456
+ optional part at a named position did not match (an unclosed paren's
457
+ `rparen`) is a `nil` attribute.
458
+
459
+ [[raw-tree]]
460
+ == The raw tree
461
+
462
+ `Amath.parse(input, decimal:, engine:)` and `Amath::Parser.raw(input,
463
+ decimal:, engine:)` return the parse tree of the legacy Plurimath grammar,
464
+ exactly as amath 0.1's `Amath.parse` returned it (Hash/Array with
465
+ `Parsanol::Slice` leaves, a plain `""` for empty input). `Amath.parse` keeps
466
+ this amath 0.1 contract unchanged, keywords included (it takes no
467
+ `dialect:`), because released Plurimath 0.11 depends on amath `~> 0.1` and
468
+ walks this tree; the typed model is `Amath.parse_model`. `Amath::RawTree` builds it from the normalized grammar's tree: it
469
+ removes every wrapper capture listed in `grammars/asciimath.wrappers.json`,
470
+ re-running Parsanol's merge of sequence results, and `Amath::Renester`
471
+ rebuilds the legacy nesting of the flat chains. Parity is checked as
472
+ `Renester.call(unwrap(raw)) == legacy tree`.
473
+
474
+ == Declared bindings and regeneration
475
+
476
+ Each entry rule puts the whole expression under one `root` capture and
477
+ declares one binding for it, `root -> expression (any)`: the complete tree as
478
+ plain data. `Amath.parse_model` applies it (`Amath.bindings`, the paired Ruby
479
+ binding artifact) and builds `Document.new(expression: ...)`; lutaml-model
480
+ constructs the nested model from the declared attribute types, with no
481
+ hand-written tree walker.
482
+
483
+ `scripts/compile.rb` compiles the grammar with `--bindings all`, which writes
484
+ one declared binding artifact per Parsanol target beside the parse artifact:
485
+
486
+ * `artifacts/asciimath.bindings.ruby.json`
487
+ * `artifacts/asciimath.bindings.rs.json`
488
+ * `artifacts/asciimath.bindings.ts.json`
489
+ * `artifacts/asciimath.bindings.python.json`
490
+
491
+ The script loads each one with Parsanol's verifier (kind, checksum, target,
492
+ binding version) and pairs it with the parse artifact (grammar, version and
493
+ source hash). With `--determinism` it compiles again and requires identical
494
+ bytes for the parse artifact and all four binding artifacts.
495
+ `artifacts/asciimath.checksums.txt` records the sha256 of every file and the
496
+ Parsanol checksum and binding version of every binding artifact. Parsanol
497
+ 1.3.130 and earlier accept `--bindings` but write no binding artifacts, so the
498
+ compiler bundle needs 1.3.131 or later.
499
+
500
+ The parse artifact also embeds the Unicode tables of the Ruby that compiled
501
+ it (its `unicode_tables` field), so identical bytes need the same Parsanol
502
+ version and the same Ruby. CI regenerates with both, read from the committed
503
+ files.