rhoella 0.1.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.
Files changed (4) hide show
  1. checksums.yaml +7 -0
  2. data/README.md +54 -0
  3. data/reference/ruby/rhoella.rb +421 -0
  4. metadata +44 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0f8dc5354e7b88622013f2d25a33bbf3bf27ec273b69995f195f463057e7f8e3
4
+ data.tar.gz: f6a2c558e09858b394ade0f50261c4c7eceae8f3795c2fc2151bfe7e9974a548
5
+ SHA512:
6
+ metadata.gz: de7a3df96bb7e73d7cf70791e169d0c2533e5d9151d56329f2f4ae75b5e83e23db4c9ac380653f65be4ac63599abeabd10379106a193091091282a89551a8ad1
7
+ data.tar.gz: d5cd12ea623d1b641a0ac3af849d96c32596a62a7de478303b30e686ff81260924e76613851d5b80e3a65985367f98bd9c3e4419cdeb3507f64808d5b0c04640
data/README.md ADDED
@@ -0,0 +1,54 @@
1
+ # rhoella
2
+
3
+ Rhoella — a minimal Fluent (FTL) engine for Metanorma.
4
+
5
+ From the Greek ῥοία (*rhoia*, flow, stream): the ideal of fluency in its
6
+ oldest root — a stream of well-formed labels. Single implementation
7
+ semantic, four runtimes:
8
+
9
+ - `reference/ruby` — the Ruby reference; the arbiter that generates the
10
+ conformance vectors, and the published `rhoella` gem
11
+ - sibling libraries, each vendoring this testsuite at a pinned ref and
12
+ running their own parity + conformance CI:
13
+ [rhoella/rhoella-py](https://github.com/rhoella/rhoella-py) (Python),
14
+ [rhoella/rhoella-rs](https://github.com/rhoella/rhoella-rs) (Rust),
15
+ [rhoella/rhoella-ts](https://github.com/rhoella/rhoella-ts)
16
+ (TypeScript, wasm-deployable pure core)
17
+
18
+ ## Supported syntax (the Fluent subset Metanorma needs)
19
+
20
+ - messages `id = pattern`; ids `[A-Za-z][A-Za-z0-9_-]*`; terms carry a
21
+ leading `-`
22
+ - multiline patterns: indented continuation lines, common indent
23
+ stripped, lines joined with "\n"
24
+ - placeables: `{ $var }`, message references `{ id }` / `{ -term }`,
25
+ selectors `{ $var -> [key] pattern ... *[other] pattern }` with
26
+ exact string matching on the selector value and a mandatory default
27
+ arm
28
+ - escapes in text: `\{`, `\}` and `\\`
29
+
30
+ ## Fluent semantics preserved
31
+
32
+ - a missing variable renders as its own literal `{ name }`
33
+ - message references resolve with the same variable bag
34
+ - resolution depth is bounded (5) and cycles raise `ResolutionError`
35
+ - a selector without a default arm is a parse error
36
+
37
+ ## Contract
38
+
39
+ `vectors/` holds the conformance vectors: FTL resources plus the
40
+ expected resolutions generated by the Ruby reference
41
+ (`tools/gen_vectors.rb`). Every runtime must reproduce every vector
42
+ exactly — success values, error classes and all. Each runtime runs the
43
+ vectors in CI (`.github/workflows/ci.yml`).
44
+
45
+ Regenerating the vectors after an intentional semantic change:
46
+
47
+ ruby tools/gen_vectors.rb
48
+
49
+ ## Runtimes
50
+
51
+ ruby -I reference/ruby -e 'require "rhoella"; puts Rhoella::Bundle.new.add_resource(File.read("testsuite/semantics/resources/core.ftl")).format("hello", "name" => "TSE")'
52
+ python3 runtimes/python/test_parity.py
53
+ (cd runtimes/rust && cargo test)
54
+ (cd runtimes/typescript && npm test)
@@ -0,0 +1,421 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rhoella
4
+ class Error < StandardError; end
5
+ class ParseError < Error; end
6
+ class ResolutionError < Error; end
7
+
8
+ # Rhoella — a minimal Fluent (FTL) engine for Metanorma (Greek rhoia: the flow).
9
+ #
10
+ # Supported syntax (the Fluent subset Metanorma needs):
11
+ # * messages: `id = pattern`, ids are [A-Za-z][A-Za-z0-9_-]*, terms are
12
+ # ids with a leading `-`
13
+ # * multiline patterns: continuation lines indented relative to the id
14
+ # line; the common indent is stripped and lines join with "\n"
15
+ # * placeables: `{ $var }`, message references `{ id }` / `{ -term }`,
16
+ # and selectors `{ $var -> [key] pattern ... *[other] pattern }`
17
+ # with exact string matching on the selector value and a mandatory
18
+ # default arm
19
+ # * escapes in text: `\{`, `\}` and `\\`
20
+ #
21
+ # Fluent semantics preserved: a missing variable renders as its own
22
+ # literal `{ name }` (soft fallback); message references resolve with
23
+ # the same variable bag; resolution depth is bounded and cycles raise.
24
+ # Formats a raw pattern string directly: parses it as a Fluent
25
+ # pattern and resolves it against the variable bag. The entry point
26
+ # for hosts whose catalogs live outside FTL resources (e.g. label
27
+ # vocabularies carrying message values).
28
+ def self.format(pattern, vars = {}, messages = {})
29
+ table = messages.transform_values do |value|
30
+ Parser.new(value).parse_elements(stop: nil)
31
+ end
32
+ Formatter.new(table, vars).format_pattern(
33
+ Parser.new(pattern).parse_elements(stop: nil), 0)
34
+ end
35
+
36
+ class Bundle
37
+ MAX_DEPTH = 5
38
+
39
+ attr_reader :messages
40
+
41
+ def initialize
42
+ @messages = {}
43
+ end
44
+
45
+ def add_resource(source)
46
+ Parser.parse(source).each { |message| @messages[message.id] = message }
47
+ self
48
+ end
49
+
50
+ def format(id, vars = {})
51
+ message = @messages[id]
52
+ raise ResolutionError, "unknown message #{id.inspect}" unless message
53
+
54
+ table = @messages.transform_values(&:pattern)
55
+ Formatter.new(table, vars).format_pattern(message.pattern, 0)
56
+ end
57
+
58
+ Message = Struct.new(:id, :pattern, keyword_init: true)
59
+ end
60
+
61
+ # Fluent parser v2: spec-shaped line machine with junk recovery.
62
+ #
63
+ # Line terminators are CR, LF and CRLF. A message block is its id
64
+ # line plus the lines that follow it: indented lines, blank lines
65
+ # and — while the pattern has unbalanced braces — any line at all
66
+ # (the placeable stays open across unindented lines). The block ends
67
+ # at a comment or an id line; an unindented non-blank line with
68
+ # balanced braces ends the block and becomes Junk. Entries whose
69
+ # joined pattern fails to parse become Junk; parsing continues.
70
+ #
71
+ # Placeables: `{ $var }`, message references `{ id }` / `{ -term }`,
72
+ # string literals `{"text"}` (with \uXXXX, \" and \\ escapes),
73
+ # number literals `{1.5}`, and selectors
74
+ # `{ $var -> [key] pattern ... *[other] pattern }` with exact
75
+ # matching and a mandatory default arm. Placeable interiors skip
76
+ # newlines: a placeable may span lines.
77
+ class Parser
78
+ ID_LINE = /\A(-?[A-Za-z][A-Za-z0-9_-]*)[ \t]*=[ \t]?(.*)\z/.freeze
79
+ COMMENT = /\A\#{1,3}/.freeze
80
+
81
+ Entry = Struct.new(:message, keyword_init: true)
82
+
83
+ class << self
84
+ def parse(source)
85
+ lines = source.split(/\r\n|\r|\n/, -1)
86
+ lines.pop if lines.last&.empty? && lines.size > 1
87
+ messages = []
88
+ block = nil
89
+ lines.each_with_index do |line, i|
90
+ if (match = ID_LINE.match(line))
91
+ messages.concat(close_block(block))
92
+ block = Block.new(id: match[1], head: match[2], lines: [])
93
+ elsif COMMENT.match?(line) || (line.strip.empty? && block.nil?)
94
+ messages.concat(close_block(block))
95
+ block = nil
96
+ elsif line.strip.empty?
97
+ next if block.nil?
98
+
99
+ # Lookahead: the blank line is interior to the block when a
100
+ # later line continues it (indented, or the pattern is
101
+ # still unbalanced); otherwise the message ends here.
102
+ j = i + 1
103
+ j += 1 while j < lines.length && lines[j].strip.empty?
104
+ nxt = lines[j]
105
+ if nxt&.match?(/\A[ \t]/) || (nxt && unbalanced?(block))
106
+ block.lines << ""
107
+ else
108
+ messages.concat(close_block(block))
109
+ block = nil
110
+ end
111
+ elsif block && (line =~ /\A[ \t]/ || unbalanced?(block))
112
+ # Continuation: indented lines, and — while the pattern has
113
+ # unbalanced braces — unindented lines too (a placeable
114
+ # stays open across them).
115
+ block.lines << line
116
+ elsif block
117
+ # An unindented, brace-balanced line ends the block; the
118
+ # line itself is junk outside any message.
119
+ messages.concat(close_block(block))
120
+ block = nil
121
+ else
122
+ # Junk outside any message: consumed, parsing continues.
123
+ end
124
+ end
125
+ messages.concat(close_block(block))
126
+ messages.compact
127
+ end
128
+
129
+ # A block closes into a Message when its joined pattern parses;
130
+ # a pattern that fails to parse is Junk — the entry is dropped
131
+ # and parsing continues.
132
+ def close_block(block)
133
+ return [] if block.nil?
134
+
135
+ [build(block)].compact
136
+ end
137
+
138
+ def build(block)
139
+ lines = [block.head] + block.lines
140
+ prefix = lines.reject(&:empty?)
141
+ .map { |l| l[/\A[ \t]+/, 0]&.length || 0 }.min || 0
142
+ stripped = lines.map { |l| l[prefix..] || "" }
143
+ stripped.shift while stripped.first&.strip&.empty? && stripped.size > 1
144
+ joined = stripped.join("\n")
145
+ pattern = new(joined).parse_elements(stop: nil)
146
+ Bundle::Message.new(id: block.id, pattern: pattern)
147
+ rescue Rhoella::Error
148
+ nil
149
+ end
150
+
151
+ def unbalanced?(block)
152
+ raw = ([block.head] + block.lines).join("\n")
153
+ open = 0
154
+ escaped_run = false
155
+ in_string = false
156
+ raw.each_char do |ch|
157
+ if in_string
158
+ in_string = false if ch == '"'
159
+ elsif ch == '"'
160
+ in_string = true
161
+ elsif ch == "{"
162
+ open += 1
163
+ elsif ch == "}"
164
+ open -= 1
165
+ end
166
+ end
167
+ open.positive?
168
+ end
169
+ end
170
+
171
+ Block = Struct.new(:id, :head, :lines, keyword_init: true)
172
+
173
+ def initialize(raw)
174
+ @raw = raw
175
+ @pos = 0
176
+ end
177
+
178
+ def parse_elements(stop:)
179
+ elements = []
180
+ buffer = +""
181
+ until @pos >= @raw.length
182
+ if stop == :arm
183
+ scan = @pos
184
+ scan += 1 while @raw[scan] =~ /[ \t\n]/
185
+ if @raw[scan] == "*" || @raw[scan] == "[" || @raw[scan] == "}"
186
+ @pos = scan
187
+ break
188
+ end
189
+ end
190
+ char = @raw[@pos]
191
+ if char == "{"
192
+ flush(buffer, elements)
193
+ buffer = +""
194
+ @pos += 1
195
+ elements << parse_placeable(stop)
196
+ elsif char == "\\" && @raw[@pos + 1] && "{}\\".include?(@raw[@pos + 1])
197
+ buffer << @raw[@pos + 1]
198
+ @pos += 2
199
+ else
200
+ buffer << char
201
+ @pos += 1
202
+ end
203
+ end
204
+ flush(buffer, elements)
205
+ merged = merge_adjacent_text(elements)
206
+ merged
207
+ end
208
+
209
+ # Adjacent literal text — including two adjacent string literals
210
+ # each carrying half of a UTF-16 surrogate pair — concatenates.
211
+ # Returns the merged element list (parse_elements' return value).
212
+ def merge_adjacent_text(elements)
213
+ merged = []
214
+ units = nil
215
+ elements.each do |element|
216
+ case element[0]
217
+ when :text
218
+ units ||= []
219
+ element[1].each_char { |c| units << c.ord }
220
+ when :units
221
+ units ||= []
222
+ units.concat(element[1])
223
+ else
224
+ merged << [:text, decode_units(units)] if units
225
+ units = nil
226
+ merged << element
227
+ end
228
+ end
229
+ merged << [:text, decode_units(units)] if units
230
+ merged
231
+ end
232
+
233
+ def decode_units(units)
234
+ out = +""
235
+ i = 0
236
+ while i < units.length
237
+ code = units[i]
238
+ if code.between?(0xD800, 0xDBFF) && units[i + 1] &&
239
+ units[i + 1].between?(0xDC00, 0xDFFF)
240
+ out << (0x10000 + ((code - 0xD800) << 10) +
241
+ (units[i + 1] - 0xDC00)).chr(Encoding::UTF_8)
242
+ i += 2
243
+ elsif code.between?(0xD800, 0xDFFF)
244
+ out << "\u{FFFD}"
245
+ i += 1
246
+ else
247
+ out << code.chr(Encoding::UTF_8)
248
+ i += 1
249
+ end
250
+ end
251
+ out
252
+ end
253
+
254
+ private
255
+
256
+ def flush(buffer, elements)
257
+ elements << [:text, buffer] unless buffer.empty?
258
+ end
259
+
260
+ def skip_placeable_spaces
261
+ @pos += 1 while @raw[@pos] =~ /[ \t\n]/
262
+ end
263
+
264
+ def parse_placeable(stop)
265
+ skip_placeable_spaces
266
+ if @raw[@pos] == '"'
267
+ return parse_string_literal
268
+ end
269
+ if @raw[@pos] =~ /[0-9-]/ && @raw[@pos..] =~ /\A-?[0-9]+(\.[0-9]+)?[ \t\n]*\}/
270
+ match = /\A(-?[0-9]+(?:\.[0-9]+)?)[ \t\n]*\}/.match(@raw[@pos..])
271
+ @pos += match[0].length
272
+ return [:text, match[1]]
273
+ end
274
+ if @raw[@pos] == "$"
275
+ @pos += 1
276
+ name = ident!
277
+ skip_placeable_spaces
278
+ if @raw[@pos, 2] == "->"
279
+ @pos += 2
280
+ return parse_select(name, stop)
281
+ end
282
+ expect!("}")
283
+ [:var, name]
284
+ elsif @raw[@pos] =~ /[A-Za-z-]/
285
+ id = ident!
286
+ skip_placeable_spaces
287
+ expect!("}")
288
+ [:ref, id]
289
+ else
290
+ raise ParseError, "unsupported placeable at #{context}"
291
+ end
292
+ end
293
+
294
+ # String literals decode as UTF-16 code units — Fluent semantics:
295
+ # a surrogate pair may straddle two adjacent string literals
296
+ # ({"\uD83D"}{"\uDE02"} is the astral emoji), so the literal keeps
297
+ # its units and adjacent text merges below.
298
+ def parse_string_literal
299
+ @pos += 1 # opening quote
300
+ units = []
301
+ loop do
302
+ raise ParseError, "unterminated string literal" if @pos >= @raw.length
303
+
304
+ char = @raw[@pos]
305
+ if char == '"'
306
+ @pos += 1
307
+ break
308
+ elsif char == "\\"
309
+ esc = @raw[@pos + 1]
310
+ if esc == "u"
311
+ hex = @raw[@pos + 2, 4]
312
+ raise ParseError, "bad unicode escape" unless hex =~ /\A[0-9A-Fa-f]{4}\z/
313
+ units << hex.to_i(16)
314
+ @pos += 6
315
+ elsif @raw[@pos + 1] && "{}\\\"".include?(esc)
316
+ units << esc.ord
317
+ @pos += 2
318
+ else
319
+ raise ParseError, "bad escape in string literal"
320
+ end
321
+ else
322
+ units << char.ord
323
+ @pos += 1
324
+ end
325
+ end
326
+ skip_placeable_spaces
327
+ expect!("}")
328
+ [:units, units]
329
+ end
330
+
331
+ def parse_select(name, _stop)
332
+ skip_placeable_spaces
333
+ variants = []
334
+ default = nil
335
+ loop do
336
+ skip_placeable_spaces
337
+ default_arm = @raw[@pos] == "*"
338
+ @pos += 1 if default_arm
339
+ unless @raw[@pos] == "["
340
+ raise ParseError, "selector arm expected at #{context}"
341
+ end
342
+ @pos += 1
343
+ close = @raw.index("]", @pos) || raise(ParseError, "unclosed arm key")
344
+ key = @raw[@pos...close].strip
345
+ @pos = close + 1
346
+ skip_placeable_spaces
347
+ elements = parse_elements(stop: :arm)
348
+ variants << [key, elements]
349
+ default = elements if default_arm
350
+ skip_placeable_spaces
351
+ if @raw[@pos] == "}"
352
+ @pos += 1
353
+ break
354
+ end
355
+ end
356
+ raise ParseError, "selector without default arm" if default.nil?
357
+
358
+ [:select, name, variants, default]
359
+ end
360
+
361
+ def ident!
362
+ unless (m = /\A[A-Za-z-][A-Za-z0-9_-]*/.match(@raw[@pos..]))
363
+ raise ParseError, "identifier expected at #{context}"
364
+ end
365
+ @pos += m[0].length
366
+ m[0]
367
+ end
368
+
369
+ def expect!(char)
370
+ raise ParseError, "expected #{char.inspect} at #{context}" unless @raw[@pos] == char
371
+
372
+ @pos += 1
373
+ end
374
+
375
+ def context
376
+ @raw[[@pos - 10, 0].max, 20].inspect
377
+ end
378
+ end
379
+
380
+ class Formatter
381
+ # `messages` maps message ids to ALREADY-PARSED pattern element
382
+ # arrays; `Bundle.format` parses its own resources into it.
383
+ def initialize(messages, vars)
384
+ @messages = messages
385
+ @vars = vars || {}
386
+ end
387
+
388
+ def format_pattern(elements, depth)
389
+ raise ResolutionError, "message nesting too deep" if depth > Bundle::MAX_DEPTH
390
+
391
+ elements.map do |element|
392
+ case element[0]
393
+ when :text then element[1]
394
+ when :var then format_var(element[1])
395
+ when :ref then format_ref(element[1], depth)
396
+ when :select then format_select(element, depth)
397
+ end
398
+ end.join
399
+ end
400
+
401
+ private
402
+
403
+ def format_var(name)
404
+ value = @vars[name]
405
+ value.nil? ? "{#{name}}" : value.to_s
406
+ end
407
+
408
+ def format_ref(id, depth)
409
+ elements = @messages[id]
410
+ raise ResolutionError, "reference to unknown message #{id.inspect}" unless elements
411
+
412
+ format_pattern(elements, depth + 1)
413
+ end
414
+
415
+ def format_select((_tag, name, variants, default), depth)
416
+ selector = format_var(name)
417
+ arm = variants.find { |(key, _)| key == selector }
418
+ format_pattern(arm ? arm[1] : default, depth + 1)
419
+ end
420
+ end
421
+ end
metadata ADDED
@@ -0,0 +1,44 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rhoella
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Metanorma
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: 'Rhoella — from the Greek rhoia, the flow — a minimal Fluent localization
13
+ engine: messages with pattern values, variable and message-reference placeables,
14
+ selectors with exact matching, bounded resolution with cycle errors.'
15
+ email:
16
+ - open.source@ribose.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - README.md
22
+ - reference/ruby/rhoella.rb
23
+ homepage: https://github.com/rhoella/rhoella
24
+ licenses:
25
+ - BSD-2-Clause
26
+ metadata: {}
27
+ rdoc_options: []
28
+ require_paths:
29
+ - reference/ruby
30
+ required_ruby_version: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ - - ">="
33
+ - !ruby/object:Gem::Version
34
+ version: '3.0'
35
+ required_rubygems_version: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ requirements: []
41
+ rubygems_version: 4.0.20
42
+ specification_version: 4
43
+ summary: 'Rhoella: a minimal Fluent (FTL) engine for Metanorma'
44
+ test_files: []