unitsml 0.6.12 → 0.6.14

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 (44) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/rake.yml +3 -0
  3. data/Gemfile +0 -1
  4. data/docs/README.adoc +221 -1
  5. data/lib/unitsml/compose/builder.rb +341 -0
  6. data/lib/unitsml/compose/composable.rb +118 -0
  7. data/lib/unitsml/compose/composite.rb +145 -0
  8. data/lib/unitsml/compose/term_tree.rb +48 -0
  9. data/lib/unitsml/compose.rb +151 -0
  10. data/lib/unitsml/conversion/definition.rb +117 -0
  11. data/lib/unitsml/conversion.rb +97 -41
  12. data/lib/unitsml/dimension.rb +30 -3
  13. data/lib/unitsml/errors/base_error.rb +11 -0
  14. data/lib/unitsml/errors/empty_composition_error.rb +14 -0
  15. data/lib/unitsml/errors/invalid_power_error.rb +37 -0
  16. data/lib/unitsml/errors/invalid_unit_entry_error.rb +44 -0
  17. data/lib/unitsml/errors/misplaced_extender_error.rb +18 -0
  18. data/lib/unitsml/errors/mixed_terms_error.rb +15 -0
  19. data/lib/unitsml/errors/parse_error.rb +18 -0
  20. data/lib/unitsml/errors/unknown_dimension_error.rb +18 -0
  21. data/lib/unitsml/errors/unknown_prefix_error.rb +15 -0
  22. data/lib/unitsml/errors/unknown_unit_error.rb +16 -0
  23. data/lib/unitsml/errors.rb +11 -0
  24. data/lib/unitsml/formula.rb +65 -4
  25. data/lib/unitsml/model/unit.rb +2 -0
  26. data/lib/unitsml/model/units/conversion_note.rb +19 -0
  27. data/lib/unitsml/model/units/conversions.rb +25 -0
  28. data/lib/unitsml/model/units/float64_conversion_from.rb +62 -0
  29. data/lib/unitsml/model/units/special_conversion_from.rb +27 -0
  30. data/lib/unitsml/model/units/wsdl_conversion_from.rb +26 -0
  31. data/lib/unitsml/model/units.rb +5 -0
  32. data/lib/unitsml/number.rb +5 -1
  33. data/lib/unitsml/opal/database_payload.rb +1 -1
  34. data/lib/unitsml/opal.rb +22 -0
  35. data/lib/unitsml/parser.rb +32 -11
  36. data/lib/unitsml/power_numerator.rb +72 -0
  37. data/lib/unitsml/quantity.rb +95 -23
  38. data/lib/unitsml/unit.rb +58 -10
  39. data/lib/unitsml/unitsdb/quantities.rb +21 -0
  40. data/lib/unitsml/unitsdb/units.rb +6 -0
  41. data/lib/unitsml/utility.rb +61 -10
  42. data/lib/unitsml/version.rb +1 -1
  43. data/lib/unitsml.rb +10 -0
  44. metadata +23 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: efbbf3687355c803f0d27613089435d0b7773d7b9a0da6b1e84205d3ffb2d3e6
4
- data.tar.gz: 74ac8457146883ac81a3b2596bbb4f16193676509c588d838c97199843ce520e
3
+ metadata.gz: 6eb7b900c878fbb336b8664d9f82f09fb4b1971e9b5bc8c5e2e53f8fa63baceb
4
+ data.tar.gz: f4b0dc34053ec9fc8d6425c26d3a86b429a05825b009ce59cd8fd30b10e427c0
5
5
  SHA512:
6
- metadata.gz: cb598545c494c983148c0cc7b604d6871b10e93b426c533bcfa3a1429e559f1a6ccda07444186a4a502699a30c9f3ea2d81995ba6ed4176de0a6e95f3aeb99fa
7
- data.tar.gz: ed77d97452ecbbccd900027206625d31057046c9c69de0c2b62771fe087e375b33aa03d13b664598dda68c5d26a68d94e0e833b14de9b43bab907a0a7f9e3857
6
+ metadata.gz: 2851de6c91a67f92f5e84b1d76efea7626d850dff7bed04d660f3522462e5859c63b88ae9ff3990560aa85efdba8d9faa3bfd3b47fba391cf819583cfaa0b0d8
7
+ data.tar.gz: ee3558da765dda1f3e7d4ae66a9b5e06e7d86b72860eae710276815c8c62d8725456895d14d6874b86dbf49f850f96e651196d81f07270fa0925edcb0cfc5f83
@@ -16,6 +16,9 @@ jobs:
16
16
  cat .bundle/config
17
17
  git clone --depth 1 https://github.com/unitsml/unitsml-testsuite.git unitsml-testsuite
18
18
  echo "CORPUS_DIR=$PWD/unitsml-testsuite/corpora/renders" >> "$GITHUB_ENV"
19
+ echo "CONVERSION_CORPUS_DIR=$PWD/unitsml-testsuite/corpora/conversions" >> "$GITHUB_ENV"
19
20
  echo "---" >> .bundle/config
20
21
  echo 'BUNDLE_BUILD__RUBY___LL: "--with-cflags=-std=gnu17"' >> .bundle/config
21
22
  cat .bundle/config
23
+ secrets:
24
+ pat_token: ${{ secrets.UNITSML_CI_PAT_TOKEN }}
data/Gemfile CHANGED
@@ -9,7 +9,6 @@ gem "canon"
9
9
  gem "nokogiri"
10
10
  gem "oga"
11
11
  gem "opal", "~> 1.8"
12
- gem "ox"
13
12
  gem "plurimath"
14
13
  gem "pry"
15
14
  gem "rake"
data/docs/README.adoc CHANGED
@@ -149,13 +149,233 @@ Prefixed units: mm, kg, μm
149
149
  A composite unit is a unit that is derived from two or more basic units
150
150
  conjoined by multiplication or division.
151
151
 
152
- Composite units are created using the `Unitsml.parse` method.
152
+ Composite units are created using the `Unitsml.parse` method, or built
153
+ programmatically (see below).
153
154
 
154
155
  Compound units with operations: kg*s^-2
155
156
  Units with powers: C^3
156
157
  Square roots: sqrt(Hz)
157
158
  Units with prefixes: m/s, m^2/s^2
158
159
 
160
+ ==== Programmatic composition
161
+
162
+ When the parts are already available as data rather than a string, composite
163
+ units can be built without parsing.
164
+
165
+ Multiplication (`*`) and division (`/`) compose units, dimensions and formulas,
166
+ returning a `Unitsml::Formula`. Like the parser, `/` keeps the `"/"` separator
167
+ and inverts the right-hand operand's power, so a single division renders
168
+ identically to the parsed string (`W / m` == `Unitsml.parse("W/m")`):
169
+
170
+ [source,ruby]
171
+ ----
172
+ # watt per metre per steradian, rendered "W/m^-1/sr^-1"
173
+ Unitsml::Unit.new("W") / Unitsml::Unit.new("m") / Unitsml::Unit.new("sr")
174
+
175
+ # m/s^2; powers come from the constructor's second argument
176
+ Unitsml::Unit.new("m") / Unitsml::Unit.new("s", 2)
177
+
178
+ # prefixes via the `prefix:` keyword
179
+ Unitsml::Unit.new("m", prefix: "k") # km
180
+ ----
181
+
182
+ The same composition can be written as a fluent chain — `#unit`/`#dimension` are
183
+ sugar over `*` (`unit("m", -1)` == `* Unit.new("m", -1)`), and
184
+ `#quantity_reference`/`#name`/`#multiplier` attach metadata. Metadata must come
185
+ last. Each chained term, and each `*` or `/`, builds a fresh `Formula` that does
186
+ not carry earlier metadata. The same holds for the comma metadata of a parsed
187
+ formula: `Unitsml.parse("W*m^-1, quantity: radiance") * Unitsml::Unit.new("sr")`
188
+ has no quantity.
189
+
190
+ [source,ruby]
191
+ ----
192
+ Unitsml::Unit.new("W").unit("m", -1).unit("sr", -1).quantity_reference("radiance")
193
+ ----
194
+
195
+ `#quantity_reference` names the NIST quantity the unit measures, emitted as a
196
+ `<Quantity>` element by `to_xml`. It is the fluent spelling of the `quantity:`
197
+ keyword of `Unitsml.compose` and of the format methods (see below), and is
198
+ unrelated to `Unitsml::Quantity`, the value-with-unit class described in the
199
+ Quantities section below.
200
+
201
+ An explicit separator can be placed between terms with `#extender` (alias
202
+ `#ext`), accepting exactly the parser's grammar set: `"*"`, `"/"` or `"//"`
203
+ (any other glyph is a display concern — use the `multiplier:` render option).
204
+ It is glyph-only: nothing is negated or transformed, so exponents are stated
205
+ explicitly, exactly as a parsed string stores them:
206
+
207
+ [source,ruby]
208
+ ----
209
+ # byte-identical to Unitsml.parse("W/m") in every format
210
+ Unitsml::Unit.new("W").extender("/").unit("m", -1)
211
+
212
+ # mixed separators, as in Unitsml.parse("W*m/W")
213
+ Unitsml::Unit.new("W").ext("*").unit("m").ext("/").unit("W", -1)
214
+ ----
215
+
216
+ The glyph may be a String, a Symbol, or an `Unitsml::Extender` object; an
217
+ `Extender` also works directly as an operator operand:
218
+
219
+ [source,ruby]
220
+ ----
221
+ Unitsml::Unit.new("W") * Unitsml::Extender.new("/") * Unitsml::Unit.new("m", -1)
222
+ ----
223
+
224
+ A separator must sit between two operands. An expression left ending in a
225
+ separator, or with two separators together, has no valid rendering and raises
226
+ `Unitsml::Errors::MisplacedExtenderError` when a `to_*` method is called (the
227
+ intermediate chain value is still usable — only rendering it is rejected):
228
+
229
+ [source,ruby]
230
+ ----
231
+ Unitsml::Unit.new("W").ext("/").to_latex # raises MisplacedExtenderError
232
+ Unitsml::Unit.new("W").ext("/").unit("m", -1).to_latex # ok — "W/m^-1"
233
+ ----
234
+
235
+ A unit is referenced by its symbol id, exactly as in a parsed string
236
+ (e.g. `"W"`). Dimensions compose the same way
237
+ (`Unitsml::Dimension.new("dim_L")`), but units and dimensions cannot be mixed in
238
+ one expression.
239
+
240
+ The `Unitsml.compose` keyword form builds the same `Formula` from a list. Pass
241
+ either `units:` or `dimensions:` (not both). A `units:` entry is a symbol id, a
242
+ `{ unit:, power:, prefix: }` hash, or a pre-built `Unitsml::Unit`; a
243
+ `dimensions:` entry is a dimension id or a `{ dimension:, power: }` hash:
244
+
245
+ [source,ruby]
246
+ ----
247
+ Unitsml.compose(
248
+ units: ["W", { unit: "m", power: -1 }, { unit: "sr", power: -1 }],
249
+ quantity: "radiance",
250
+ )
251
+
252
+ Unitsml.compose(dimensions: ["dim_L", { dimension: "dim_M", power: 2 }])
253
+ ----
254
+
255
+ The `quantity`, `name` and `multiplier` metadata are also accepted directly by
256
+ the format methods. They apply to `to_xml` (`quantity`/`name` are ignored by the
257
+ other formats), and a value passed at render time overrides one carried by a
258
+ parsed comma-metadata expression:
259
+
260
+ [source,ruby]
261
+ ----
262
+ formula = Unitsml.compose(units: ["W", { unit: "m", power: -1 }])
263
+ formula.to_xml(quantity: "radiance") # emits a <Quantity> element
264
+ ----
265
+
266
+ The fluent `#unit`/`#dimension` chain and the keyword form join terms with `*`,
267
+ turning division into a negative exponent, so they render like `W*m^-1`. (The
268
+ `/` operator and explicit `#extender`/`#ext` separators keep their glyph
269
+ instead — see above.) Where terms are `*`-joined, the separator is a display
270
+ choice — pass the `multiplier:` argument to any `to_*` method (`:space`,
271
+ `:nospace`, or a custom string such as `"·"`) to change it:
272
+
273
+ [source,ruby]
274
+ ----
275
+ formula = Unitsml::Unit.new("W").unit("m", -1)
276
+ formula.to_asciimath # => "W*m^-1"
277
+ formula.to_asciimath(multiplier: :space) # => "W m^-1"
278
+ formula.to_asciimath(multiplier: "·") # => "W·m^-1"
279
+ ----
280
+
281
+ `Unitsml.compose` and the fluent chain validate every reference, power and
282
+ prefix, and the `name` and `multiplier` metadata. They raise a
283
+ `Unitsml::Errors::*` (all subclasses of `Unitsml::Errors::BaseError`) for
284
+ anything they cannot resolve: an unknown unit, dimension or prefix, a
285
+ units/dimensions mix, an empty composition, a power the parser cannot express
286
+ (a decimal exponent — use a `Rational`), or a non-string `name`/`multiplier`.
287
+ `Unit.new`/`Dimension.new` validate their own reference, prefix and power on
288
+ construction too, so an unresolvable value raises immediately whichever surface
289
+ you use. A `Unitsml::Number` power must hold a number (`Number.new("abc")`
290
+ raises).
291
+
292
+ The `quantity` metadata is looked up when `to_xml` runs, by NIST id (such as
293
+ `"NISTq1"`) or by English name (such as `"radiance"`). A value that matches no
294
+ quantity is not an error: `to_xml` leaves out the `<Quantity>` element.
295
+
296
+ ==== Text of composed units
297
+
298
+ A composed `Formula` keeps its original term tree for rendering, so `to_latex`,
299
+ `to_xml` and the other formats are not affected by the text described here.
300
+
301
+ Its `norm_text` is a flat list of the unit leaves joined by `*`, with each
302
+ stored power written in parentheses. This text parses back into the same units,
303
+ prefixes and power values. A single division of two plain units keeps the
304
+ familiar form. A square root is written as its exponent, so a composed
305
+ `sqrt(Hz)` becomes `Hz^(5/10)`: the parsed text has the same power, but renders
306
+ without the root sign.
307
+
308
+ [source,ruby]
309
+ ----
310
+ (Unitsml::Unit.new("m") / Unitsml::Unit.new("s")).norm_text # => "m/s"
311
+ (Unitsml::Unit.new("W") / Unitsml::Unit.new("m") / Unitsml::Unit.new("sr")).norm_text
312
+ # => "W*m^(-1)*sr^(-1)"
313
+ ----
314
+
315
+ The `norm_text` of a parsed `Formula` is unchanged.
316
+
317
+ ==== Quantities
318
+
319
+ `Unitsml::Quantity` pairs a value with a unit. The unit can be given with the
320
+ `unit:` keyword as a string, a `Unitsml::Unit` or a `Unitsml::Formula`. A string
321
+ is parsed. A `Unit` or `Formula` is used without parsing. The older
322
+ `unit_expression:` keyword still accepts a string. Give only one of the two
323
+ keywords. Without a unit, or with `unit: nil`, the quantity is a pure number.
324
+ `unit:` does not take a bare `Unitsml::Dimension`; build a dimension quantity
325
+ from a `Formula`, for example
326
+ `unit: Unitsml.compose(dimensions: ["dim_L"])`.
327
+
328
+ [source,ruby]
329
+ ----
330
+ Unitsml::Quantity.new(value: 10, unit: "kV")
331
+ Unitsml::Quantity.new(value: 10, unit: Unitsml::Unit.new("V", prefix: "k"))
332
+ Unitsml::Quantity.new(value: 3, unit: Unitsml::Unit.new("m") / Unitsml::Unit.new("s"))
333
+ Unitsml::Quantity.new(value: 10, unit_expression: "kV")
334
+ ----
335
+
336
+ A `Formula` passed in is kept as the same object, so changing it later also
337
+ changes the quantity. Results of arithmetic always get their own copy.
338
+
339
+ Multiplying or dividing a `Unit`, `Dimension` or `Formula` by a number, on
340
+ either side, gives a `Unitsml::Quantity` with that number as its value. A
341
+ quantity can also be multiplied or divided by a bare `Unit`, `Dimension` or
342
+ `Formula`, which counts as a value of 1. Nothing is parsed. Units and
343
+ dimensions still cannot be mixed, and anything else raises
344
+ `Unitsml::Errors::InvalidUnitEntryError`.
345
+
346
+ [source,ruby]
347
+ ----
348
+ metre = Unitsml::Unit.new("m")
349
+ second = Unitsml::Unit.new("s")
350
+
351
+ 5 * metre # => Quantity, value 5, unit m
352
+ metre / 2.0 # => Quantity, value 0.5, unit m
353
+ 5 / second # => Quantity, value 5, unit s^-1
354
+
355
+ distance = Unitsml::Quantity.new(value: 6, unit: metre)
356
+ distance / second # => Quantity, value 6, unit m/s
357
+ ----
358
+
359
+ Two units without a number still compose into a `Formula`, as described above.
360
+
361
+ Multiplying or dividing two quantities composes their units with the same
362
+ builder as `Unit#*` and `Unit#/`, and nothing is reparsed from text. The
363
+ resulting `norm_text` follows the rules above:
364
+
365
+ [source,ruby]
366
+ ----
367
+ w_per_m = Unitsml::Quantity.new(value: 6, unit: "W/m")
368
+ s = Unitsml::Quantity.new(value: 2, unit: "s")
369
+ (w_per_m * s).norm_text # => "W*m^(-1)*s"
370
+ ----
371
+
372
+ Some behavior is unchanged and is tracked in issue #82. Fractional powers and
373
+ square roots are not handled exactly in `dimension_vector` and `dimension_id`.
374
+ Dimension leaves such as `dim_L` do not contribute to `dimension_vector`, and
375
+ dividing by a dimension does not invert it. Adding or subtracting two interval
376
+ scale quantities still returns a ratio scale result. Quantities with a unit and
377
+ a dimension cannot be combined and raise `Unitsml::Errors::MixedTermsError`.
378
+
159
379
 
160
380
  === Format representation
161
381
 
@@ -0,0 +1,341 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ module Compose
5
+ # Assembles composed root Formulas for both the operator DSL (build_product)
6
+ # and the keyword form (from_terms). Each leaf is REBUILT with its final
7
+ # power computed up front (coerce, negate for division, drop an
8
+ # inversion-produced ^1); the builder only READS operands and constructs
9
+ # fresh objects, so it can never mutate a caller's operand and never runs an
10
+ # in-place negation on shared state. Branch structure is rebuilt via
11
+ # TermTree; leaf text lives on Unit/Dimension.
12
+ module Builder
13
+ class << self
14
+ # Combine a left term list with the right operand's terms. The operator
15
+ # glyph itself joins the two sides (like the parser: `a / b` keeps the
16
+ # "/" and inverts b's power; `a * b` keeps "*"). An explicit trailing
17
+ # extender on the left (from #extender) already is the join, so no glyph
18
+ # is inserted after it — but `/` still inverts the right-hand side.
19
+ # An empty side inserts no glyph.
20
+ def build_product(left_terms, right_terms, operator)
21
+ left = build_terms(left_terms, invert: false)
22
+ right = build_terms(right_terms, invert: operator == "/")
23
+ joiner = join_glyph(left, right, operator)
24
+ build_root_formula(left + joiner + right)
25
+ end
26
+
27
+ # Quantity arithmetic adapter: a nil formula (pure number) is an empty
28
+ # side of the same build_product engine. nil op nil stays nil.
29
+ def quantity_product(left, right, operator)
30
+ return nil unless left || right
31
+
32
+ build_product(left ? left.value : [], right ? right.value : [],
33
+ operator)
34
+ end
35
+
36
+ # Independent copy of a Formula (tree, powers, prefixes, text and
37
+ # metadata) without parsing; its norm_text is kept, not re-synthesized.
38
+ def copy_formula(formula)
39
+ return nil unless formula
40
+
41
+ copy = TermTree.map_leaves(formula) { |leaf| copy_leaf(leaf) }
42
+ copy.norm_text = formula.norm_text&.dup
43
+ copy.explicit_value = formula.explicit_value&.dup
44
+ copy
45
+ end
46
+
47
+ # Append an explicit (pre-validated) separator glyph to the term list,
48
+ # exactly as the parser stores it. Glyph-only: no transformation.
49
+ def append_extender(terms, symbol)
50
+ left = build_terms(terms, invert: false)
51
+ build_root_formula(left + [Extender.new(symbol)])
52
+ end
53
+
54
+ # Build a root Formula from an ordered list of unit/dimension operands,
55
+ # interleaving multiplication between them.
56
+ def from_terms(operands, quantity: nil, name: nil, multiplier: nil)
57
+ terms = interleave(build_terms(operands, invert: false))
58
+ build_root_formula(terms, build_metadata(quantity, name, multiplier))
59
+ end
60
+
61
+ # Return a Formula carrying the given render metadata (quantity/name/
62
+ # multiplier). A Formula gets a copy with merged metadata; a lone
63
+ # Unit/Dimension is wrapped into a root Formula. Backs the fluent
64
+ # #quantity_reference/#name/#multiplier chain methods.
65
+ def attach_metadata(node, **extras)
66
+ return from_terms([node], **extras) unless node.is_a?(Formula)
67
+
68
+ added = build_metadata(extras[:quantity], extras[:name],
69
+ extras[:multiplier])
70
+ # A deep copy, so the result never shares terms with the caller's
71
+ # Formula (a shallow dup would share the term array and leaves).
72
+ copy = copy_formula(node)
73
+ copy.explicit_value = merge_metadata(node.explicit_value, added)
74
+ copy
75
+ end
76
+
77
+ private
78
+
79
+ def merge_metadata(existing, added)
80
+ merged = (existing || {}).merge(added || {})
81
+ merged.empty? ? nil : merged
82
+ end
83
+
84
+ # orig_text keeps the parser-style source text (and every renderer
85
+ # keeps the original tree); norm_text is a flat, re-parseable leaf
86
+ # list so a composed expression survives a parse round trip.
87
+ def build_root_formula(terms, metadata = nil)
88
+ reject_mixed_terms!(terms)
89
+ Formula.new(terms, explicit_value: metadata, root: true,
90
+ orig_text: terms_text(terms),
91
+ norm_text: norm_leaves_text(terms))
92
+ end
93
+
94
+ # --- leaf reconstruction (via TermTree.map_leaves) -----------------
95
+
96
+ # Rebuild every operand: map_leaves reconstructs branch wrappers and
97
+ # each Unit/Dimension leaf is copied with a freshly built final power
98
+ # (and a duplicated prefix). Non-leaf terms (Extender/Number) plain-dup.
99
+ def build_terms(terms, invert:)
100
+ TermTree.map_leaves(terms) { |leaf| rebuild_leaf(leaf, invert) }
101
+ end
102
+
103
+ def join_glyph(left, right, operator)
104
+ return [] if left.empty? || right.empty? || left.last.is_a?(Extender)
105
+
106
+ [Extender.new(operator)]
107
+ end
108
+
109
+ def copy_leaf(leaf)
110
+ rebuild_leaf(leaf, false)
111
+ end
112
+
113
+ # Every copied term owns its strings too (names, prefix, exponent
114
+ # lexemes), so mutating a result in place never reaches an operand.
115
+ def rebuild_leaf(leaf, invert)
116
+ case leaf
117
+ when Unit then rebuild_unit(leaf, invert)
118
+ when Dimension
119
+ copy = leaf.dup
120
+ copy.dimension_name = leaf.dimension_name.dup
121
+ copy.power_numerator = final_power(leaf.power_numerator, invert)
122
+ copy
123
+ else copy_term(leaf)
124
+ end
125
+ end
126
+
127
+ def rebuild_unit(leaf, invert)
128
+ copy = leaf.dup
129
+ copy.unit_name = leaf.unit_name.dup
130
+ copy.power_numerator = final_power(leaf.power_numerator, invert)
131
+ copy.prefix = copy_prefix(leaf.prefix) if leaf.prefix
132
+ copy
133
+ end
134
+
135
+ def copy_prefix(prefix)
136
+ copy = prefix.dup
137
+ copy.prefix_name = prefix.prefix_name.dup
138
+ copy
139
+ end
140
+
141
+ def copy_term(term)
142
+ case term
143
+ when Number then Number.new(term.raw_value.dup)
144
+ when Extender then Extender.new(term.symbol.dup)
145
+ else term.dup
146
+ end
147
+ end
148
+
149
+ # The leaf's final exponent as a fresh Number (or nil). For division the
150
+ # exponent is negated; a negation that resolves to +1 (dividing by a
151
+ # ^-1 term) renders as no exponent, matching the parser, so it is
152
+ # dropped. A non-inverted explicit ^1 is preserved.
153
+ def final_power(power, invert)
154
+ if power.is_a?(Fenced)
155
+ return copy_fenced_power(power) unless invert
156
+
157
+ raw = fenced_raw(power)
158
+ else
159
+ raw = power_string(power)
160
+ end
161
+ return raw && Number.new(raw.dup) unless invert
162
+
163
+ negated = negate_string(raw)
164
+ negated == "1" ? nil : Number.new(negated)
165
+ end
166
+
167
+ # A parser-produced Fenced exponent (e.g. m^((1/2))): its innermost
168
+ # lexeme, read through any number of nested wrappers.
169
+ def fenced_raw(power)
170
+ power.is_a?(Fenced) ? fenced_raw(power.value) : power_string(power)
171
+ end
172
+
173
+ # Deep copy of a non-inverted Fenced exponent, wrappers preserved.
174
+ def copy_fenced_power(power)
175
+ inner = power.value
176
+ inner = if inner.is_a?(Fenced) then copy_fenced_power(inner)
177
+ else copy_term(inner)
178
+ end
179
+ Fenced.new(power.open_paren, inner, power.close_paren)
180
+ end
181
+
182
+ # A builder-supplied power as a parser-style exponent string (or nil):
183
+ # 1 -> "1", 1/2 -> "1/2", 2.0 -> "2". A non-integer Float is rejected
184
+ # (the parser has no decimal exponent); an existing Number is read by
185
+ # value, never shared.
186
+ def power_string(power)
187
+ case power
188
+ when nil then nil
189
+ when Number then power.raw_value
190
+ when Integer then power.to_s
191
+ when Rational then rational_string(power)
192
+ when Float then float_string(power)
193
+ else raise Errors::InvalidPowerError.new(value: power)
194
+ end
195
+ end
196
+
197
+ def float_string(power)
198
+ unless power.finite? && power == power.to_i
199
+ raise Errors::InvalidPowerError.new(value: power,
200
+ reason: :non_integer_float)
201
+ end
202
+
203
+ power.to_i.to_s
204
+ end
205
+
206
+ def rational_string(power)
207
+ power.denominator == 1 ? power.numerator.to_s : power.to_s
208
+ end
209
+
210
+ # Negate an exponent string: nil (no exponent) -> "-1", zero stays
211
+ # "0" (never "-0"), else flip sign.
212
+ def negate_string(raw)
213
+ return "-1" if raw.nil?
214
+ return raw if raw.match?(/\A-?0+\z/)
215
+
216
+ raw.start_with?("-") ? raw.delete_prefix("-") : "-#{raw}"
217
+ end
218
+
219
+ # --- unit/dimension mixing guard (via TermTree.each_leaf) ----------
220
+
221
+ # Units and dimensions cannot share one expression (the XML serializer
222
+ # would drop the unit block); a single walk collects the leaf kinds.
223
+ def reject_mixed_terms!(terms)
224
+ kinds = leaf_kinds(terms)
225
+ return unless kinds.include?(Unit) && kinds.include?(Dimension)
226
+
227
+ raise Errors::MixedTermsError
228
+ end
229
+
230
+ def leaf_kinds(terms)
231
+ kinds = []
232
+ TermTree.each_leaf(terms) do |leaf|
233
+ kinds << leaf.class if leaf.is_a?(Unit) || leaf.is_a?(Dimension)
234
+ end
235
+ kinds
236
+ end
237
+
238
+ # --- text synthesis ------------------------------------------------
239
+
240
+ # Reconstruct parser-style source text; leaf text lives on the domain
241
+ # objects (Unit/Dimension#xml_postprocess_name) and branches wrap their
242
+ # inner text. Recurses over the same tree shape as TermTree.
243
+ def terms_text(term)
244
+ case term
245
+ when Array then term.map { |child| terms_text(child) }.join
246
+ when Unit, Dimension then term.xml_postprocess_name
247
+ when Extender then term.symbol
248
+ else branch_text(term)
249
+ end
250
+ end
251
+
252
+ # Flat norm_text: the simple Unit / Unit shape keeps its familiar
253
+ # text (m/s); anything else lists every ordered leaf with its stored
254
+ # power, joined by "*". Wrappers (Fenced/Sqrt/Formula) contribute only
255
+ # their stored leaves; powers are copied lexically, never evaluated.
256
+ def norm_leaves_text(terms)
257
+ return simple_division_text(terms) if simple_division?(terms)
258
+
259
+ leaves = []
260
+ TermTree.each_leaf(terms) do |leaf|
261
+ case leaf
262
+ when Unit, Dimension then leaves << leaf_norm_text(leaf)
263
+ when Number then leaves << leaf.raw_value
264
+ end
265
+ end
266
+ leaves.join("*")
267
+ end
268
+
269
+ def simple_division?(terms)
270
+ return false unless terms.size == 3
271
+
272
+ numerator, glyph, denominator = terms
273
+ numerator.is_a?(Unit) && numerator.power_numerator.nil? &&
274
+ glyph.is_a?(Extender) && glyph.symbol == "/" &&
275
+ simple_denominator?(denominator)
276
+ end
277
+
278
+ def simple_denominator?(term)
279
+ power = term.power_numerator if term.is_a?(Unit)
280
+ power.is_a?(Number) && power.raw_value == "-1"
281
+ end
282
+
283
+ def simple_division_text(terms)
284
+ "#{unit_text(terms[0])}/#{unit_text(terms[2])}"
285
+ end
286
+
287
+ def unit_text(unit)
288
+ "#{unit.prefix_name}#{unit.unit_name}"
289
+ end
290
+
291
+ def leaf_norm_text(leaf)
292
+ name = leaf.is_a?(Unit) ? unit_text(leaf) : leaf.dimension_name
293
+ power = leaf.power_numerator
294
+ raw = power && decimal_as_fraction(fenced_raw(power))
295
+ raw ? "#{name}^(#{raw})" : name
296
+ end
297
+
298
+ # A finite decimal lexeme (0.5) is not a parser exponent; write it as
299
+ # the lexical fraction 5/10 by digit placement, with no Float math.
300
+ def decimal_as_fraction(raw)
301
+ return raw unless raw.match?(/\A-?\d+\.\d+\z/)
302
+
303
+ sign = raw.start_with?("-") ? "-" : ""
304
+ whole, fraction = raw.delete_prefix("-").split(".")
305
+ numerator = "#{whole}#{fraction}".sub(/\A0+(?=\d)/, "")
306
+ "#{sign}#{numerator}/#{10**fraction.size}"
307
+ end
308
+
309
+ def branch_text(term)
310
+ case term
311
+ when Fenced
312
+ "#{term.open_paren}#{terms_text(term.value)}#{term.close_paren}"
313
+ when Sqrt then "sqrt(#{terms_text(term.value)})"
314
+ when Formula then terms_text(term.value)
315
+ else ""
316
+ end
317
+ end
318
+
319
+ # --- small helpers -------------------------------------------------
320
+
321
+ def interleave(operands)
322
+ operands.each_with_index.flat_map do |operand, index|
323
+ index.zero? ? [operand] : [mul_extender, operand]
324
+ end
325
+ end
326
+
327
+ def build_metadata(quantity, name, multiplier)
328
+ Compose.validate_name!(name)
329
+ Compose.validate_multiplier!(multiplier)
330
+ metadata = { quantity: quantity, name: name,
331
+ multiplier: multiplier }.compact
332
+ metadata.empty? ? nil : metadata
333
+ end
334
+
335
+ def mul_extender
336
+ Extender.new("*")
337
+ end
338
+ end
339
+ end
340
+ end
341
+ end