unitsml 0.6.11 → 0.6.13

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 (46) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/rake.yml +5 -0
  3. data/Gemfile +0 -1
  4. data/docs/README.adoc +234 -1
  5. data/lib/unitsml/compose/builder.rb +347 -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 +332 -0
  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/quantity_errors.rb +1 -0
  21. data/lib/unitsml/errors/unknown_dimension_error.rb +18 -0
  22. data/lib/unitsml/errors/unknown_prefix_error.rb +15 -0
  23. data/lib/unitsml/errors/unknown_unit_error.rb +16 -0
  24. data/lib/unitsml/errors.rb +11 -0
  25. data/lib/unitsml/formula.rb +65 -4
  26. data/lib/unitsml/model/unit.rb +2 -0
  27. data/lib/unitsml/model/units/conversion_note.rb +19 -0
  28. data/lib/unitsml/model/units/conversions.rb +25 -0
  29. data/lib/unitsml/model/units/float64_conversion_from.rb +62 -0
  30. data/lib/unitsml/model/units/special_conversion_from.rb +27 -0
  31. data/lib/unitsml/model/units/wsdl_conversion_from.rb +26 -0
  32. data/lib/unitsml/model/units.rb +5 -0
  33. data/lib/unitsml/number.rb +5 -1
  34. data/lib/unitsml/opal/database_payload.rb +1 -1
  35. data/lib/unitsml/opal.rb +23 -0
  36. data/lib/unitsml/parg/tree_mapper.rb +31 -1
  37. data/lib/unitsml/parser.rb +12 -1
  38. data/lib/unitsml/power_numerator.rb +61 -0
  39. data/lib/unitsml/quantity.rb +122 -22
  40. data/lib/unitsml/unit.rb +60 -4
  41. data/lib/unitsml/unitsdb/quantities.rb +21 -0
  42. data/lib/unitsml/unitsdb/units.rb +6 -0
  43. data/lib/unitsml/utility.rb +61 -10
  44. data/lib/unitsml/version.rb +1 -1
  45. data/lib/unitsml.rb +11 -0
  46. metadata +24 -2
@@ -0,0 +1,332 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ # Canonical unit conversion (R-A3): reduces a parsed unit expression to
5
+ # its SI-referenced canonical composition using the unitsdb
6
+ # canonical_conversion data (unitsdb schema 2.1.0), prefix factors and
7
+ # si_derived_bases/root_units chains.
8
+ #
9
+ # Semantics: value_target = value * factor + offset. The additive offset
10
+ # exists only for affine scales (temperature) and is permitted only when
11
+ # the whole expression is that single unit with power 1 — an affine unit
12
+ # inside a composite raises.
13
+ module Conversion
14
+ autoload :Definition, "unitsml/conversion/definition"
15
+
16
+ Result = Struct.new(:factor, :offset, keyword_init: true)
17
+
18
+ module_function
19
+
20
+ # The dispatch walkers mirror the grammar's case structure; the
21
+ # branchiness is inherent and gated by the conformance suite.
22
+ # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/MethodLength, Layout/LineLength, Lint/DuplicateBranch, Lint/ElseLayout
23
+
24
+ # Returns a Result for the parsed expression. definitions: an
25
+ # optional hash of unit identifiers (register ids or symbols) to
26
+ # Conversion::Definition (or Float64ConversionFrom model) instances;
27
+ # a definition replaces the canonical factor/offset for its unit so
28
+ # the two paths are never applied in sequence.
29
+ def to_canonical(formula, definitions: nil)
30
+ walk(formula, 1, definitions: definitions)
31
+ end
32
+
33
+ def walk(node, sign, definitions: nil)
34
+ case node
35
+ when Formula
36
+ # The parser already normalizes "/" and "//" by inverting the
37
+ # following exponents (update_units_exponents), so the tree walks
38
+ # multiplicatively with no sign tracking.
39
+ node.value.reduce(Result.new(factor: Rational(1), offset: 0)) do |acc, part|
40
+ next acc if part.is_a?(Extender)
41
+
42
+ merge(acc, walk_with_sign(part, sign, definitions: definitions))
43
+ end
44
+ when Fenced
45
+ walk(node.value, sign, definitions: definitions)
46
+ when Sqrt
47
+ sub = walk(node.value, sign, definitions: definitions)
48
+ Result.new(factor: sqrt_rational(sub.factor), offset: sub.offset)
49
+ when Extender
50
+ Result.new(factor: Rational(1), offset: 0)
51
+ when Unit
52
+ unit_result(node, sign, definitions: definitions)
53
+ when Dimension, Number_, Prefix
54
+ Result.new(factor: Rational(1), offset: 0)
55
+ else
56
+ raise Errors::ConversionError, "cannot convert #{node.class} node"
57
+ end
58
+ end
59
+
60
+ def walk_with_sign(part, sign, definitions: nil)
61
+ result = walk(part, sign, definitions: definitions)
62
+ sign.negative? ? Result.new(factor: 1 / result.factor, offset: 0) : result
63
+ end
64
+
65
+ def merge(left, right)
66
+ if (left.offset != 0 && right.factor != 1) || (right.offset != 0 && left.factor != 1)
67
+ raise Errors::ConversionError,
68
+ "affine unit inside a composite expression"
69
+ end
70
+
71
+ Result.new(
72
+ factor: left.factor * right.factor,
73
+ offset: left.offset + right.offset,
74
+ )
75
+ end
76
+
77
+ def unit_result(unit, _sign, definitions: nil)
78
+ prefix_factor = if unit.prefix
79
+ Rational(unit.prefix.base)**unit.prefix.power
80
+ else
81
+ Rational(1)
82
+ end
83
+ power = node_power(unit.power_numerator)
84
+ record = unit.unit_instance
85
+ unless record
86
+ raise Errors::ConversionError,
87
+ "unknown unit #{unit.unit_name.inspect}"
88
+ end
89
+
90
+ # A supplied definition replaces the canonical factor/offset for its
91
+ # unit — the two paths are never applied in sequence; when the
92
+ # register also carries canonical data, the two must agree.
93
+ if (definition = definition_for(record, definitions))
94
+ def_factor, def_offset = definition_result(definition, power, record)
95
+ return Result.new(factor: def_factor * (prefix_factor**power),
96
+ offset: def_offset)
97
+ end
98
+
99
+ # The prefix scales with the unit power: 1 km2 = 1 000 000 m2, not
100
+ # 1 000 m2 — the prefix is as squared as the unit is.
101
+ factor, offset = record_factor(record, power, [record_identity(record)])
102
+ factor *= prefix_factor**power
103
+ Result.new(factor: factor, offset: offset)
104
+ end
105
+
106
+ # The definition supplied for this record, if any. Lookup keys are the
107
+ # register ids and symbols of the record.
108
+ def definition_for(record, definitions)
109
+ return nil if definitions.nil? || definitions.empty?
110
+
111
+ keys = record.identifiers.to_a.map(&:id) +
112
+ record.symbols.to_a.map(&:id)
113
+ entry = keys.filter_map { |key| definitions[key.to_s] }.first
114
+ return nil if entry.nil?
115
+
116
+ case entry
117
+ when Definition then entry
118
+ when Model::Units::Float64ConversionFrom then Definition.new(entry)
119
+ else Definition.from_model(entry)
120
+ end
121
+ end
122
+
123
+ # The definition expressed as a canonical SI-anchored Result for the
124
+ # unit carrying it: value_SI = f_i((c / b)^p value - d) - f_i a + o_i,
125
+ # where (f_i, o_i) is the initial unit's canonical Result. Affine
126
+ # definitions (non-zero addends) are legal only at power 1; purely
127
+ # multiplicative definitions power legally.
128
+ def definition_result(definition, power, record)
129
+ a = Rational(definition.model.lexical_decimal(:initial_addend))
130
+ b = Rational(definition.model.lexical_decimal(:multiplicand))
131
+ c = Rational(definition.model.lexical_decimal(:divisor))
132
+ d = Rational(definition.model.lexical_decimal(:final_addend))
133
+ if (a != 0 || d != 0) && power != 1
134
+ raise Errors::ConversionError,
135
+ "affine unit raised to power #{power}"
136
+ end
137
+
138
+ factor = (c / b)**power
139
+ offset = a.zero? && d.zero? ? Rational(0) : (-(c / b) * d) - a
140
+ initial = definition.initial_unit_record
141
+ initial_factor, initial_offset = record_factor(initial, 1)
142
+ computed = [initial_factor * factor, (initial_offset * factor) + offset]
143
+ agree!(record, definition, power, computed)
144
+ computed
145
+ end
146
+
147
+ # A definition and the register's canonical data describing the same
148
+ # unit must agree; disagreement is a diagnostic, not a silent choice.
149
+ # Both are taken at the same power. Canonical offsets are
150
+ # decimal-truncated register data, so the comparison uses the
151
+ # importer's 1e-9 relative tolerance.
152
+ def agree!(record, definition, power, computed)
153
+ return unless record.canonical_conversion
154
+
155
+ factor, offset = record_factor(record, power)
156
+ agreed = [factor, offset].zip(computed).all? do |ours, theirs|
157
+ delta = (ours - theirs).abs
158
+ delta.zero? || delta <= ours.abs / Rational(10**9)
159
+ end
160
+ return if agreed
161
+
162
+ raise Errors::ConversionError,
163
+ "conversion definition #{definition.model.id.inspect} " \
164
+ "disagrees with canonical data for " \
165
+ "#{record.symbols&.first&.id.inspect}: canonical " \
166
+ "(#{factor}, #{offset}) vs definition (#{computed[0]}, " \
167
+ "#{computed[1]})"
168
+ end
169
+
170
+ # [multiplicative factor, additive offset] for one unit record at the
171
+ # given power. Cyclic derivations (e.g. a unit defined in terms of
172
+ # itself) have no linear canonical conversion and raise.
173
+ def record_identity(record)
174
+ record.identifiers&.map { |i| "#{i.type}:#{i.id}" }&.sort&.join("|")
175
+ end
176
+
177
+ def record_factor(record, power, _visited = [])
178
+ cc = record.canonical_conversion
179
+ return conversion_factor(cc, power) if cc
180
+
181
+ bases = record.si_derived_bases
182
+ bases = record.root_units if bases.nil? || bases.empty?
183
+ if bases.nil? || bases.empty?
184
+ system = record.unit_system_reference&.first&.id.to_s
185
+ if Lutaml::Model::Utils.snake_case(system) == "si_base"
186
+ return [Rational(1),
187
+ Rational(0)]
188
+ end
189
+
190
+ raise Errors::ConversionError,
191
+ "no canonical conversion path for #{record.symbols&.first&.id.inspect}"
192
+ end
193
+
194
+ factor = Rational(1)
195
+ bases.each do |base|
196
+ base_power = (base.power || 1) * power
197
+ prefix_factor = prefix_factor_from_reference(base.prefix_reference)
198
+ sub_factor, sub_offset = base_factor(base.unit_reference, base_power)
199
+ if sub_offset != 0
200
+ raise Errors::ConversionError,
201
+ "affine unit inside a derived composition"
202
+ end
203
+
204
+ # sub_factor already carries base_power (base_factor exponentiates the
205
+ # canonical factor by it); prefix scales with the base power too, so a
206
+ # squared prefixed unit squares its prefix (km2 -> 1 000 000 m2).
207
+ factor *= (prefix_factor**base_power) * sub_factor
208
+ end
209
+ [factor, Rational(0)]
210
+ end
211
+
212
+ def conversion_factor(cc, power)
213
+ if cc.offset && cc.offset != "0" && power != 1
214
+ raise Errors::ConversionError, "affine unit raised to power #{power}"
215
+ end
216
+
217
+ factor = Rational(cc.factor)**power
218
+ offset = Rational(cc.offset || 0)
219
+ [factor, offset]
220
+ end
221
+
222
+ def base_factor(unit_reference, power)
223
+ record = Unitsml::Unitsdb.units.find_by_id(unit_reference.id)
224
+ raise Errors::ConversionError, "unknown conversion target" unless record
225
+
226
+ record_factor(record, power)
227
+ end
228
+
229
+ def prefix_factor_from_reference(reference)
230
+ return Rational(1) if reference.nil?
231
+
232
+ record = Unitsml::Unitsdb.prefixes.find_by_id(reference.id)
233
+ return Rational(1) unless record
234
+
235
+ Rational(record.base)**record.power
236
+ end
237
+
238
+ def node_power(numerator)
239
+ return 1 if numerator.nil?
240
+
241
+ numerator.raw_value.to_s.to_r
242
+ end
243
+
244
+ def sqrt_rational(rational)
245
+ root = Integer.sqrt(rational.numerator)
246
+ den = Integer.sqrt(rational.denominator)
247
+ if root * root == rational.numerator && den * den == rational.denominator
248
+ Rational(root, den)
249
+ else
250
+ raise Errors::ConversionError,
251
+ "square root of #{rational} is not rational"
252
+ end
253
+ end
254
+
255
+ # Dimension-only decomposition (no factors): the same entry shape
256
+ # Utility.units2dimensions returns, for units that canonical data can
257
+ # reduce but the legacy decomposition cannot. nil when any unit has
258
+ # no path.
259
+ def dimension_entries(formula)
260
+ entries = []
261
+ collect_units(formula.value).each do |unit|
262
+ dims = unit_dimensions(
263
+ unit.unit_instance,
264
+ node_power(unit.power_numerator),
265
+ [],
266
+ )
267
+ return nil if dims.nil?
268
+
269
+ entries.concat(dims)
270
+ end
271
+ summed = Hash.new(0)
272
+ symbols = {}
273
+ entries.each do |entry|
274
+ summed[entry[:dimension]] += entry[:exponent]
275
+ symbols[entry[:dimension]] ||= entry[:symbol]
276
+ end
277
+ summed.map do |dimension, exponent|
278
+ { dimension: dimension, symbol: symbols[dimension], exponent: exponent }
279
+ end
280
+ end
281
+
282
+ def collect_units(value)
283
+ value.flat_map do |node|
284
+ case node
285
+ when Unit then [node]
286
+ when Formula then collect_units(node.value)
287
+ when Fenced then collect_units([node.value])
288
+ when Sqrt then node.value.is_a?(Unit) ? [node.value] : []
289
+ else []
290
+ end
291
+ end
292
+ end
293
+
294
+ def unit_dimensions(record, power, visited)
295
+ return nil if record.nil? || visited.include?(record.object_id)
296
+
297
+ visited = visited + [record.object_id]
298
+ sym = record.symbols&.first&.id
299
+ if (u2d = Unitsml::Utility::U2D[sym])
300
+ return [{ dimension: u2d[:dimension], symbol: u2d[:symbol],
301
+ exponent: power }]
302
+ end
303
+
304
+ if (cc = record.canonical_conversion)
305
+ dims = []
306
+ cc.root_units.each do |root|
307
+ target = Unitsml::Unitsdb.units.find_by_id(root.unit_reference.id)
308
+ sub = unit_dimensions(target, (root.power || 1) * power, visited)
309
+ return nil if sub.nil?
310
+
311
+ dims.concat(sub)
312
+ end
313
+ return dims
314
+ end
315
+
316
+ chains = record.si_derived_bases
317
+ chains = record.root_units if chains.nil? || chains.empty?
318
+ return nil if chains.nil? || chains.empty?
319
+
320
+ dims = []
321
+ chains.each do |base|
322
+ target = Unitsml::Unitsdb.units.find_by_id(base.unit_reference.id)
323
+ sub = unit_dimensions(target, (base.power || 1) * power, visited)
324
+ return nil if sub.nil?
325
+
326
+ dims.concat(sub)
327
+ end
328
+ dims
329
+ end
330
+ # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/MethodLength, Layout/LineLength, Lint/DuplicateBranch, Lint/ElseLayout
331
+ end
332
+ end
@@ -3,12 +3,14 @@
3
3
  module Unitsml
4
4
  class Dimension
5
5
  include MathmlHelper
6
+ include Compose::Composable
7
+ include PowerNumerator
6
8
 
7
- attr_accessor :dimension_name, :power_numerator
9
+ attr_accessor :dimension_name
8
10
 
9
11
  def initialize(dimension_name, power_numerator = nil)
10
- @dimension_name = dimension_name
11
- @power_numerator = power_numerator
12
+ @dimension_name = safe_dimension_name(dimension_name)
13
+ self.power_numerator = power_numerator
12
14
  end
13
15
 
14
16
  def ==(other)
@@ -79,8 +81,33 @@ module Unitsml
79
81
  value&.split("_")&.map(&:capitalize)&.join
80
82
  end
81
83
 
84
+ # Parser-style source text for the dimension, e.g. "dim_L" or "dim_L^2".
85
+ # Mirrors Unit#xml_postprocess_name so composed text is built the same way.
86
+ def xml_postprocess_name
87
+ "#{dimension_name}#{display_exp}"
88
+ end
89
+
82
90
  private
83
91
 
92
+ # Resolve a dimension reference to a known parsable id, as Unit#resolve_ref
93
+ # does for units: a pathological name (BasicObject / bad #to_s) or an
94
+ # unresolvable one fails fast as UnknownDimensionError instead of crashing
95
+ # at render on a nil dim_instance. The parser only ever supplies ids the
96
+ # grammar produced, so valid names pass through unchanged.
97
+ def safe_dimension_name(name)
98
+ string = Compose.safe_string(name)
99
+ return string if string && Unitsdb.dimensions.parsables.key?(string)
100
+
101
+ raise Errors::UnknownDimensionError.new(value: name)
102
+ end
103
+
104
+ def display_exp
105
+ return unless power_numerator
106
+
107
+ exp = power_numerator.raw_value
108
+ "^#{exp}" if exp != "1"
109
+ end
110
+
84
111
  def html_numerator_conversion(options)
85
112
  "<sup>#{power_numerator.to_html(options)}</sup>"
86
113
  end
@@ -3,6 +3,17 @@
3
3
  module Unitsml
4
4
  module Errors
5
5
  class BaseError < StandardError
6
+ private
7
+
8
+ # Render a user-supplied value for an error message without letting a
9
+ # pathological #inspect (one that raises, or a BasicObject that has none)
10
+ # escape as a non-Errors::* exception while building the message.
11
+ def describe(value)
12
+ rendered = value.inspect
13
+ rendered.is_a?(String) ? rendered : "(unprintable value)"
14
+ rescue StandardError
15
+ "(unprintable value)"
16
+ end
6
17
  end
7
18
  end
8
19
  end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ module Errors
5
+ # Raised when Unitsml.compose is given nothing to build from — neither a
6
+ # non-empty units: nor dimensions: list.
7
+ class EmptyCompositionError < Unitsml::Errors::BaseError
8
+ def initialize(msg = nil)
9
+ super(msg || "[unitsml] Nothing to compose — supply a non-empty " \
10
+ "`units:` or `dimensions:` list.")
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ module Errors
5
+ # Raised when a builder-supplied power cannot become a parser-style
6
+ # exponent: an unsupported type, or a non-integer / non-finite Float (the
7
+ # parser has no decimal exponent — pass a Rational instead).
8
+ class InvalidPowerError < Unitsml::Errors::BaseError
9
+ attr_reader :value, :reason
10
+
11
+ def initialize(value:, reason: :unsupported_type)
12
+ @value = value
13
+ @reason = reason
14
+ super(message_for(reason, value))
15
+ end
16
+
17
+ private
18
+
19
+ def message_for(reason, value)
20
+ case reason
21
+ when :non_integer_float
22
+ "[unitsml] Non-integer Float power: #{describe(value)} — use a " \
23
+ "Rational (e.g. Rational(1, 2)) for a fractional exponent."
24
+ when :invalid_number
25
+ "[unitsml] Invalid Number power: #{describe(value)} — a Number " \
26
+ "exponent must hold an integer or n/m fraction (e.g. \"2\", \"1/2\")."
27
+ when :unsupported_storage
28
+ "[unitsml] Cannot store #{describe(value)} as an exponent — " \
29
+ "expected a Numeric, Unitsml::Number, or Unitsml::Fenced."
30
+ else
31
+ "[unitsml] Unsupported power: #{describe(value)} — expected an " \
32
+ "Integer, Rational, Float or Unitsml::Number."
33
+ end
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ module Errors
5
+ # Raised when a compose entry (or operator operand) is not something the
6
+ # builder can turn into a term: the wrong type, the wrong kind for the mode
7
+ # (a Dimension in units: / a Unit in dimensions:), a prefix on a dimension,
8
+ # or a non-composable `*`/`/` operand (unit DSL or Quantity arithmetic).
9
+ class InvalidUnitEntryError < Unitsml::Errors::BaseError
10
+ attr_reader :value, :field
11
+
12
+ def initialize(value:, field: :entry)
13
+ @value = value
14
+ @field = field
15
+ super(message_for(field, value))
16
+ end
17
+
18
+ # Message per field; %s is the described value.
19
+ MESSAGES = {
20
+ operand: "[unitsml] Cannot compose with %s — not a supported " \
21
+ "operand for this operator.",
22
+ prefix: "[unitsml] A dimension cannot take a prefix: %s.",
23
+ multiplier: "[unitsml] Invalid multiplier: %s — expected a String, " \
24
+ ":space, or :nospace.",
25
+ name: "[unitsml] Invalid name: %s — expected a String or Symbol.",
26
+ unit: "[unitsml] Invalid unit: %s — expected a String, Unit or " \
27
+ "Formula.",
28
+ extender: "[unitsml] Invalid extender: %s — expected \"*\", \"/\" " \
29
+ "or \"//\"; custom separators are a render option " \
30
+ "(multiplier:).",
31
+ }.freeze
32
+
33
+ private
34
+
35
+ def message_for(field, value)
36
+ template = MESSAGES.fetch(field) do
37
+ "[unitsml] Invalid #{field} entry: %s — expected a reference " \
38
+ "(String/Symbol), a Hash, or a matching Unit/Dimension."
39
+ end
40
+ format(template, describe(value))
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ module Errors
5
+ # Raised at render time when a composed Formula puts a separator (extender)
6
+ # where no operand follows it: the expression ends with an extender ("W/"),
7
+ # or two extenders sit together ("W/*"). Such a term list has no valid
8
+ # rendering; only a raw extender chain (#extender/#ext or an Extender
9
+ # operand) can build one — the parser grammar never produces it.
10
+ class MisplacedExtenderError < Unitsml::Errors::BaseError
11
+ def initialize(text = nil)
12
+ super(text || "[unitsml] Composed expression has a separator " \
13
+ "(extender) with no operand after it; it cannot be " \
14
+ "rendered.")
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ module Errors
5
+ # Raised when a composition mixes units and dimensions in one expression.
6
+ # The XML serializer emits only the dimension block for such a mix, silently
7
+ # dropping the units; the parser rejects the same input outright.
8
+ class MixedTermsError < Unitsml::Errors::BaseError
9
+ def initialize(msg = nil)
10
+ super(msg || "[unitsml] Cannot combine units and dimensions in a " \
11
+ "single expression.")
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ module Errors
5
+ # Raised by Unitsml.parse for text that is not a UnitsML expression. The
6
+ # parser's own error (Parsanol::ParseFailed) is kept as #cause, so
7
+ # callers rescue this class instead of the parser library's.
8
+ class ParseError < BaseError
9
+ attr_reader :text
10
+
11
+ def initialize(text)
12
+ @text = text
13
+ super("[unitsml] Error: cannot parse #{text.inspect} as a UnitsML " \
14
+ "expression.")
15
+ end
16
+ end
17
+ end
18
+ end
@@ -6,5 +6,6 @@ module Unitsml
6
6
  class DimensionMismatchError < QuantityOperationError; end
7
7
  class ScaleOperationError < QuantityOperationError; end
8
8
  class IndeterminateResultError < QuantityOperationError; end
9
+ class ConversionError < QuantityOperationError; end
9
10
  end
10
11
  end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ module Errors
5
+ # Raised when a dimension reference cannot be resolved — by Dimension.new
6
+ # (which validates its name against the parsable ids) or by the compose
7
+ # validators, which fail fast with the same error before construction.
8
+ class UnknownDimensionError < Unitsml::Errors::BaseError
9
+ attr_reader :value
10
+
11
+ def initialize(value:)
12
+ @value = value
13
+ super("[unitsml] Unknown dimension reference: #{describe(value)} — " \
14
+ "expected a dimension id (e.g. \"dim_L\").")
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ module Errors
5
+ class UnknownPrefixError < Unitsml::Errors::BaseError
6
+ attr_reader :value, :field
7
+
8
+ def initialize(value:, field: :prefix)
9
+ @value = value
10
+ @field = field
11
+ super("[unitsml] Unknown prefix reference: #{describe(value)}.")
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ module Errors
5
+ class UnknownUnitError < Unitsml::Errors::BaseError
6
+ attr_reader :value, :field
7
+
8
+ def initialize(value:, field: :unit)
9
+ @value = value
10
+ @field = field
11
+ super("[unitsml] Unknown unit reference: #{describe(value)} — " \
12
+ "expected a unit symbol id (e.g. \"W\").")
13
+ end
14
+ end
15
+ end
16
+ end
@@ -3,15 +3,26 @@
3
3
  module Unitsml
4
4
  module Errors
5
5
  autoload :BaseError, "unitsml/errors/base_error"
6
+ autoload :ConversionError, "unitsml/errors/quantity_errors"
7
+ autoload :EmptyCompositionError, "unitsml/errors/empty_composition_error"
6
8
  autoload :InvalidModelError, "unitsml/errors/invalid_model_error"
9
+ autoload :InvalidPowerError, "unitsml/errors/invalid_power_error"
10
+ autoload :InvalidUnitEntryError, "unitsml/errors/invalid_unit_entry_error"
11
+ autoload :MisplacedExtenderError,
12
+ "unitsml/errors/misplaced_extender_error"
13
+ autoload :MixedTermsError, "unitsml/errors/mixed_terms_error"
7
14
  autoload :OpalPayloadNotBundledError,
8
15
  "unitsml/errors/opal_payload_not_bundled_error"
9
16
  autoload :PlurimathLoadError, "unitsml/errors/plurimath_load_error"
10
17
  autoload :PargLoadError, "unitsml/errors/parg_load_error"
18
+ autoload :ParseError, "unitsml/errors/parse_error"
11
19
  autoload :QuantityOperationError, "unitsml/errors/quantity_errors"
12
20
  autoload :DimensionMismatchError, "unitsml/errors/quantity_errors"
13
21
  autoload :ScaleOperationError, "unitsml/errors/quantity_errors"
14
22
  autoload :IndeterminateResultError, "unitsml/errors/quantity_errors"
23
+ autoload :UnknownDimensionError, "unitsml/errors/unknown_dimension_error"
24
+ autoload :UnknownPrefixError, "unitsml/errors/unknown_prefix_error"
25
+ autoload :UnknownUnitError, "unitsml/errors/unknown_unit_error"
15
26
  autoload :UnsupportedPayloadTypeError,
16
27
  "unitsml/errors/unsupported_payload_type_error"
17
28
  end