libo11y 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.
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "generated/goprint"
4
+
5
+ module Libo11y
6
+ module Spec
7
+ module GoQuote
8
+ SHORT_ESCAPES = {
9
+ "\a" => '\a',
10
+ "\b" => '\b',
11
+ "\f" => '\f',
12
+ "\n" => '\n',
13
+ "\r" => '\r',
14
+ "\t" => '\t',
15
+ "\v" => '\v'
16
+ }.freeze
17
+
18
+ module_function
19
+
20
+ def printable?(codepoint)
21
+ ranges = GO_PRINT_RANGES
22
+ lo = 0
23
+ hi = ranges.length
24
+ while lo < hi
25
+ mid = (lo + hi) >> 1
26
+ if ranges[mid] < codepoint
27
+ lo = mid + 1
28
+ else
29
+ hi = mid
30
+ end
31
+ end
32
+ lo < ranges.length && (lo.odd? || ranges[lo] == codepoint)
33
+ end
34
+
35
+ def quote(str)
36
+ out = +"\""
37
+ str.each_char do |ch|
38
+ cp = ch.ord
39
+ if ["\"", "\\"].include?(ch)
40
+ out << "\\" << ch
41
+ elsif printable?(cp)
42
+ out << ch
43
+ elsif (short = SHORT_ESCAPES[ch])
44
+ out << short
45
+ elsif cp < 0x20 || cp == 0x7F
46
+ out << format("\\x%02x", cp)
47
+ elsif cp < 0x10000
48
+ out << format("\\u%04x", cp)
49
+ else
50
+ out << format("\\U%08x", cp)
51
+ end
52
+ end
53
+ out << "\""
54
+ out
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,468 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "psych"
4
+
5
+ module Libo11y
6
+ module Spec
7
+ # yaml.v3-compatible YAML event composer and scalar resolver for application registries.
8
+ module YamlV3
9
+ class SyntaxError < StandardError; end
10
+
11
+ INVALID_CHAR_RE = /[^\t\n\r\x20-\x7e\u0085\u00a0-\ud7ff\ue000-\ufffd\u{10000}-\u{10ffff}]/
12
+
13
+ ScalarNode = Struct.new(:tag, :value, :quoted_or_block, :anchor, keyword_init: true)
14
+ SequenceNode = Struct.new(:tag, :items, :anchor, keyword_init: true)
15
+ MappingNode = Struct.new(:tag, :pairs, :anchor, keyword_init: true)
16
+ AliasNode = Struct.new(:anchor, keyword_init: true)
17
+ Document = Struct.new(:root, :explicit_start, :version, :aliases, keyword_init: true)
18
+ ScalarValue = Data.define(:is_null, :text, :is_string)
19
+
20
+ LONG_TAG_PREFIX = "tag:yaml.org,2002:"
21
+ TAG_NULL = "!!null"
22
+ TAG_BOOL = "!!bool"
23
+ TAG_STR = "!!str"
24
+ TAG_INT = "!!int"
25
+ TAG_FLOAT = "!!float"
26
+ TAG_TIMESTAMP = "!!timestamp"
27
+ TAG_BINARY = "!!binary"
28
+ TAG_MERGE = "!!merge"
29
+
30
+ RESOLVABLE_TAGS = ["", TAG_STR, TAG_BOOL, TAG_INT, TAG_FLOAT, TAG_NULL, TAG_TIMESTAMP].to_h { |t| [t, true] }.freeze
31
+ MERGE_TAGS = ["", "!", TAG_MERGE].to_h { |t| [t, true] }.freeze
32
+
33
+ RESOLVE_MAP = {
34
+ "true" => TAG_BOOL, "True" => TAG_BOOL, "TRUE" => TAG_BOOL,
35
+ "false" => TAG_BOOL, "False" => TAG_BOOL, "FALSE" => TAG_BOOL,
36
+ "" => TAG_NULL, "~" => TAG_NULL, "null" => TAG_NULL, "Null" => TAG_NULL, "NULL" => TAG_NULL,
37
+ ".nan" => TAG_FLOAT, ".NaN" => TAG_FLOAT, ".NAN" => TAG_FLOAT,
38
+ ".inf" => TAG_FLOAT, ".Inf" => TAG_FLOAT, ".INF" => TAG_FLOAT,
39
+ "+.inf" => TAG_FLOAT, "+.Inf" => TAG_FLOAT, "+.INF" => TAG_FLOAT,
40
+ "-.inf" => TAG_FLOAT, "-.Inf" => TAG_FLOAT, "-.INF" => TAG_FLOAT,
41
+ "<<" => TAG_MERGE
42
+ }.freeze
43
+
44
+ INT64_MAX = (1 << 63) - 1
45
+ UINT64_MAX = (1 << 64) - 1
46
+ YAML_STYLE_FLOAT_RE = /\A[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?\z/
47
+ DOT_FLOAT_RE = /\A\.[0-9]+([eE][-+]?[0-9]+)?\z/
48
+ BASE64_RE = %r{\A(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?\z}
49
+ TIMESTAMP_RES = [
50
+ /\A(\d{4})-(\d\d?)-(\d\d?)T(\d\d?):(\d\d?):(\d\d?)(?:[.,]\d+)?(Z|[+-](\d\d):(\d\d))\z/,
51
+ /\A(\d{4})-(\d\d?)-(\d\d?)t(\d\d?):(\d\d?):(\d\d?)(?:[.,]\d+)?(Z|[+-](\d\d):(\d\d))\z/,
52
+ /\A(\d{4})-(\d\d?)-(\d\d?) (\d\d?):(\d\d?):(\d\d?)(?:[.,]\d+)?\z/,
53
+ /\A(\d{4})-(\d\d?)-(\d\d?)\z/
54
+ ].freeze
55
+
56
+ ALIAS_RATIO_LOW = 400_000.0
57
+ ALIAS_RATIO_HIGH = 4_000_000.0
58
+ MAX_DEPTH = 10_000
59
+
60
+ class Handler < Psych::Handler
61
+ attr_reader :docs
62
+
63
+ def initialize
64
+ super
65
+ @docs = []
66
+ @stack = []
67
+ @anchors = {}
68
+ @aliases = {}
69
+ @doc_explicit = false
70
+ @doc_version = nil
71
+ @doc_root = nil
72
+ end
73
+
74
+ def start_document(version, _tag_directives, implicit)
75
+ raise SyntaxError, "found incompatible YAML document" if version && !version.empty? && version != [1, 1]
76
+
77
+ @doc_version = version && !version.empty? ? version : nil
78
+ @doc_explicit = !implicit
79
+ @anchors = {}
80
+ @aliases = {}
81
+ @stack = []
82
+ @doc_root = nil
83
+ end
84
+
85
+ def end_document(_implicit)
86
+ @docs << Document.new(
87
+ root: @doc_root,
88
+ explicit_start: @doc_explicit,
89
+ version: @doc_version,
90
+ aliases: @aliases
91
+ )
92
+ end
93
+
94
+ def scalar(value, anchor, tag, plain, quoted, style)
95
+ quoted_or_block = quoted || !plain || (style != Psych::Nodes::Scalar::PLAIN)
96
+ node = ScalarNode.new(tag: tag, value: value, quoted_or_block: quoted_or_block, anchor: anchor)
97
+ @anchors[anchor] = node if anchor
98
+ attach(node)
99
+ end
100
+
101
+ def alias(anchor)
102
+ target = @anchors[anchor]
103
+ raise SyntaxError, "unknown anchor '#{anchor}' referenced" unless target
104
+
105
+ node = AliasNode.new(anchor: anchor)
106
+ @aliases[node.object_id] = target
107
+ attach(node)
108
+ end
109
+
110
+ def start_sequence(anchor, tag, _implicit, _style)
111
+ raise SyntaxError, "the document nests too deeply" if @stack.length >= MAX_DEPTH
112
+
113
+ node = SequenceNode.new(tag: tag, items: [], anchor: anchor)
114
+ @anchors[anchor] = node if anchor
115
+ attach(node)
116
+ @stack << [:seq, node]
117
+ end
118
+
119
+ def end_sequence
120
+ @stack.pop
121
+ end
122
+
123
+ def start_mapping(anchor, tag, _implicit, _style)
124
+ raise SyntaxError, "the document nests too deeply" if @stack.length >= MAX_DEPTH
125
+
126
+ node = MappingNode.new(tag: tag, pairs: [], anchor: anchor)
127
+ @anchors[anchor] = node if anchor
128
+ attach(node)
129
+ @stack << [:map, node, nil]
130
+ end
131
+
132
+ def end_mapping
133
+ @stack.pop
134
+ end
135
+
136
+ private
137
+
138
+ def attach(node)
139
+ if @stack.empty?
140
+ @doc_root = node
141
+ return
142
+ end
143
+ top = @stack.last
144
+ if top[0] == :seq
145
+ top[1].items << node
146
+ elsif top[2].nil?
147
+ top[2] = node
148
+ else
149
+ top[1].pairs << [top[2], node]
150
+ top[2] = nil
151
+ end
152
+ end
153
+ end
154
+
155
+ module_function
156
+
157
+ def decode_input(raw)
158
+ bytes = raw.b
159
+ text = if bytes.start_with?("\xFF\xFE".b)
160
+ decode_utf(bytes.byteslice(2, bytes.bytesize - 2), Encoding::UTF_16LE)
161
+ elsif bytes.start_with?("\xFE\xFF".b)
162
+ decode_utf(bytes.byteslice(2, bytes.bytesize - 2), Encoding::UTF_16BE)
163
+ elsif bytes.start_with?("\xEF\xBB\xBF".b)
164
+ decode_utf(bytes.byteslice(3, bytes.bytesize - 3), Encoding::UTF_8)
165
+ else
166
+ decode_utf(bytes, Encoding::UTF_8)
167
+ end
168
+ check_characters(text)
169
+ text
170
+ end
171
+
172
+ def decode_utf(bytes, enc)
173
+ str = bytes.dup.force_encoding(enc)
174
+ raise SyntaxError, "invalid #{enc.name} input" unless str.valid_encoding?
175
+
176
+ str.encode(Encoding::UTF_8)
177
+ rescue Encoding::InvalidByteSequenceError, Encoding::UndefinedConversionError
178
+ raise SyntaxError, "invalid #{enc.name} input"
179
+ end
180
+
181
+ def check_characters(text)
182
+ return unless (m = INVALID_CHAR_RE.match(text))
183
+
184
+ cp = m[0].ord
185
+ raise SyntaxError, format("control characters are not allowed: U+%04X", cp)
186
+ end
187
+
188
+ # Adjust libyaml's YAML 1.1 double-quoted escapes to match Go's yaml.v3:
189
+ # - Reject `\/` (yaml.v3 rejects escaped slash; libyaml accepts it)
190
+ # - Rewrite `\'` inside double-quoted strings to `'` (yaml.v3 accepts it; libyaml rejects it)
191
+ # - Reject `\uD800`-`\uDFFF` surrogate escapes
192
+ def preprocess_double_quoted_escapes(text)
193
+ out = String.new(encoding: Encoding::UTF_8, capacity: text.bytesize)
194
+ i = 0
195
+ len = text.length
196
+ in_single = false
197
+ in_double = false
198
+ in_comment = false
199
+
200
+ while i < len
201
+ ch = text[i]
202
+ if in_comment
203
+ out << ch
204
+ in_comment = false if ["\n", "\r"].include?(ch)
205
+ i += 1
206
+ elsif in_single
207
+ out << ch
208
+ if ch == "'"
209
+ if i + 1 < len && text[i + 1] == "'"
210
+ out << "'"
211
+ i += 2
212
+ else
213
+ in_single = false
214
+ i += 1
215
+ end
216
+ else
217
+ i += 1
218
+ end
219
+ elsif in_double
220
+ if ch == "\\"
221
+ raise SyntaxError, "unterminated escape in double-quoted scalar" if i + 1 >= len
222
+
223
+ nxt = text[i + 1]
224
+ if nxt == "/"
225
+ raise SyntaxError, "found unknown escape character '/'"
226
+ elsif nxt == "'"
227
+ out << "'"
228
+ i += 2
229
+ elsif nxt == "u" && i + 5 < len
230
+ hex = text[i + 2, 4]
231
+ if /\A[0-9a-fA-F]{4}\z/.match?(hex)
232
+ cp = hex.to_i(16)
233
+ raise SyntaxError, "found invalid Unicode character escape code" if cp.between?(0xD800, 0xDFFF)
234
+ end
235
+ out << ch << nxt
236
+ i += 2
237
+ else
238
+ out << ch << nxt
239
+ i += 2
240
+ end
241
+ else
242
+ out << ch
243
+ in_double = false if ch == "\""
244
+ i += 1
245
+ end
246
+ else
247
+ if ch == "#" && (i.zero? || text[i - 1] == " " || text[i - 1] == "\t" || text[i - 1] == "\n" || text[i - 1] == "\r")
248
+ in_comment = true
249
+ elsif ch == "'"
250
+ in_single = true
251
+ elsif ch == "\""
252
+ in_double = true
253
+ end
254
+ out << ch
255
+ i += 1
256
+ end
257
+ end
258
+ out
259
+ end
260
+
261
+ def parse_documents(text)
262
+ check_characters(text)
263
+ normalized = preprocess_double_quoted_escapes(text)
264
+ handler = Handler.new
265
+ parser = Psych::Parser.new(handler)
266
+ parser.parse(normalized)
267
+ handler.docs
268
+ rescue Psych::Exception => e
269
+ raise SyntaxError, e.message
270
+ end
271
+
272
+ def short_tag(tag)
273
+ return "" if tag.nil?
274
+ return "!!#{tag.delete_prefix(LONG_TAG_PREFIX)}" if tag.start_with?(LONG_TAG_PREFIX)
275
+
276
+ tag
277
+ end
278
+
279
+ def hint(s)
280
+ return "N" if s.empty?
281
+
282
+ c = s[0]
283
+ return "S" if ["+", "-"].include?(c)
284
+ return "D" if c.between?("0", "9")
285
+ return "M" if "yYnNtTfFoO~".include?(c)
286
+
287
+ c == "." ? "." : ""
288
+ end
289
+
290
+ def parse_digits(s, base)
291
+ return nil if s.empty?
292
+
293
+ n = 0
294
+ s.each_byte do |b|
295
+ d = if b.between?(0x30, 0x39)
296
+ b - 0x30
297
+ elsif b.between?(0x61, 0x7A)
298
+ b - 0x61 + 10
299
+ elsif b.between?(0x41, 0x5A)
300
+ b - 0x41 + 10
301
+ else
302
+ return nil
303
+ end
304
+ return nil if d >= base
305
+
306
+ n = (n * base) + d
307
+ end
308
+ n
309
+ end
310
+
311
+ def go_parse_uint(s, base)
312
+ return nil if s.empty?
313
+
314
+ b = base
315
+ digits = s
316
+ if base.zero?
317
+ b = 10
318
+ if s[0] == "0"
319
+ p = s.length > 1 ? s[1].downcase : ""
320
+ if s.length >= 3 && p == "b"
321
+ b = 2
322
+ digits = s[2..]
323
+ elsif s.length >= 3 && p == "o"
324
+ b = 8
325
+ digits = s[2..]
326
+ elsif s.length >= 3 && p == "x"
327
+ b = 16
328
+ digits = s[2..]
329
+ else
330
+ b = 8
331
+ digits = s[1..]
332
+ return 0 if digits.empty? && s == "0"
333
+ end
334
+ end
335
+ end
336
+ n = parse_digits(digits, b)
337
+ return nil if n.nil? || n > UINT64_MAX
338
+
339
+ n
340
+ end
341
+
342
+ def go_parse_int(s, base)
343
+ return nil if s.empty?
344
+
345
+ negative = s[0] == "-"
346
+ body = ["+", "-"].include?(s[0]) ? s[1..] : s
347
+ n = go_parse_uint(body, base)
348
+ return nil if n.nil?
349
+
350
+ limit = negative ? INT64_MAX + 1 : INT64_MAX
351
+ return nil if n > limit
352
+
353
+ negative ? -n : n
354
+ end
355
+
356
+ def finite_float?(s)
357
+ Float(s).finite?
358
+ rescue ArgumentError
359
+ false
360
+ end
361
+
362
+ def days_in(month, year)
363
+ if month == 2
364
+ return (year % 4).zero? && (!(year % 100).zero? || (year % 400).zero?) ? 29 : 28
365
+ end
366
+
367
+ [4, 6, 9, 11].include?(month) ? 30 : 31
368
+ end
369
+
370
+ def parse_timestamp?(s)
371
+ return false if s.length < 5 || !/\A\d{4}-/.match?(s)
372
+
373
+ TIMESTAMP_RES.each do |pattern|
374
+ m = pattern.match(s)
375
+ next unless m
376
+
377
+ year = m[1].to_i
378
+ month = m[2].to_i
379
+ day = m[3].to_i
380
+ hour = m.size > 4 && m[4] ? m[4].to_i : 0
381
+ minute = m.size > 5 && m[5] ? m[5].to_i : 0
382
+ second = m.size > 6 && m[6] ? m[6].to_i : 0
383
+ next unless month.between?(1, 12) && day >= 1 && day <= days_in(month, year)
384
+ next if hour > 23 || minute > 59 || second > 59
385
+ next if m.size > 9 && m[8] && m[9] && (m[8].to_i > 24 || m[9].to_i > 60)
386
+
387
+ return true
388
+ end
389
+ false
390
+ end
391
+
392
+ def classify(tag, s)
393
+ h = hint(s)
394
+ return [TAG_STR, false] if h.empty? || tag == TAG_STR
395
+
396
+ mapped = RESOLVE_MAP[s]
397
+ return [mapped, false] if mapped
398
+
399
+ return [TAG_FLOAT, false] if h == "." && DOT_FLOAT_RE.match?(s) && finite_float?(s)
400
+
401
+ if %w[D S].include?(h)
402
+ return [TAG_TIMESTAMP, false] if (tag.empty? || tag == TAG_TIMESTAMP) && parse_timestamp?(s)
403
+
404
+ plain = s.delete("_")
405
+ return [TAG_INT, false] unless go_parse_int(plain, 0).nil?
406
+ return [TAG_INT, true] unless go_parse_uint(plain, 0).nil?
407
+ return [TAG_FLOAT, false] if YAML_STYLE_FLOAT_RE.match?(plain) && finite_float?(plain)
408
+
409
+ if plain.start_with?("0b")
410
+ return [TAG_INT, false] unless go_parse_int(plain[2..], 2).nil?
411
+ return [TAG_INT, true] unless go_parse_uint(plain[2..], 2).nil?
412
+ elsif plain.start_with?("-0b") && !go_parse_int("-#{plain[3..]}", 2).nil?
413
+ return [TAG_INT, false]
414
+ end
415
+ if plain.start_with?("0o")
416
+ return [TAG_INT, false] unless go_parse_int(plain[2..], 8).nil?
417
+ return [TAG_INT, true] unless go_parse_uint(plain[2..], 8).nil?
418
+ elsif plain.start_with?("-0o") && !go_parse_int("-#{plain[3..]}", 8).nil?
419
+ return [TAG_INT, false]
420
+ end
421
+ end
422
+ [TAG_STR, false]
423
+ end
424
+
425
+ def decode_base64(s)
426
+ compact = s.delete("\r\n")
427
+ raise SyntaxError, "!!binary value contains invalid base64 data" unless BASE64_RE.match?(compact)
428
+
429
+ raw = compact.unpack1("m0")
430
+ raw.force_encoding(Encoding::UTF_8).encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
431
+ end
432
+
433
+ def resolve_scalar(tag, value, quoted_or_block)
434
+ short = short_tag(tag)
435
+ if short == TAG_STR || ((short.empty? || short == "!") && quoted_or_block)
436
+ return ScalarValue.new(is_null: false, text: value, is_string: true)
437
+ end
438
+
439
+ unless RESOLVABLE_TAGS[short]
440
+ return ScalarValue.new(is_null: false, text: decode_base64(value), is_string: true) if short == TAG_BINARY
441
+
442
+ return ScalarValue.new(is_null: false, text: value, is_string: true)
443
+ end
444
+
445
+ resolved_tag, unsigned = classify(short, value)
446
+ resolved_tag = TAG_FLOAT if short == TAG_FLOAT && resolved_tag == TAG_INT && !unsigned
447
+ raise SyntaxError, "cannot decode #{resolved_tag} `#{value}` as a #{short}" if !short.empty? && short != resolved_tag
448
+ return ScalarValue.new(is_null: true, text: "", is_string: false) if resolved_tag == TAG_NULL
449
+
450
+ ScalarValue.new(is_null: false, text: value, is_string: [TAG_STR, TAG_MERGE].include?(resolved_tag))
451
+ end
452
+
453
+ def allowed_alias_ratio(decodes)
454
+ return 0.99 if decodes <= ALIAS_RATIO_LOW
455
+ return 0.10 if decodes >= ALIAS_RATIO_HIGH
456
+
457
+ 0.99 - (0.89 * ((decodes - ALIAS_RATIO_LOW) / (ALIAS_RATIO_HIGH - ALIAS_RATIO_LOW)))
458
+ end
459
+
460
+ def merge_key?(node)
461
+ node.is_a?(ScalarNode) &&
462
+ !node.quoted_or_block &&
463
+ node.value == "<<" &&
464
+ MERGE_TAGS[short_tag(node.tag)]
465
+ end
466
+ end
467
+ end
468
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "spec/generated/spec"
4
+ require_relative "spec/generated/tables"
5
+ require_relative "spec/generated/goprint"
6
+ require_relative "spec/go_quote"
7
+ require_relative "spec/app_registry"
8
+
9
+ module Libo11y
10
+ module Spec
11
+ end
12
+ end