field_struct 0.15.0 → 1.0.0.pre1

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 (70) hide show
  1. checksums.yaml +4 -4
  2. data/.claude-plugin/marketplace.json +13 -0
  3. data/.claude-plugin/plugin.json +9 -0
  4. data/AGENTS.md +47 -54
  5. data/CHANGELOG.md +53 -640
  6. data/LICENSE.txt +21 -0
  7. data/README.md +33 -628
  8. data/USAGE.md +771 -715
  9. data/docs/getting_started.md +139 -325
  10. data/lib/field_struct/base.rb +241 -1149
  11. data/lib/field_struct/class_macros.rb +163 -0
  12. data/lib/field_struct/describer.rb +167 -0
  13. data/lib/field_struct/errors.rb +182 -62
  14. data/lib/field_struct/exceptions.rb +40 -0
  15. data/lib/field_struct/field.rb +69 -135
  16. data/lib/field_struct/field_builder.rb +110 -0
  17. data/lib/field_struct/field_checks.rb +50 -0
  18. data/lib/field_struct/introspection.rb +199 -0
  19. data/lib/field_struct/json_codec.rb +240 -0
  20. data/lib/field_struct/metadata.rb +65 -260
  21. data/lib/field_struct/model_name.rb +27 -27
  22. data/lib/field_struct/option_checker.rb +121 -0
  23. data/lib/field_struct/partial.rb +49 -0
  24. data/lib/field_struct/presence.rb +45 -0
  25. data/lib/field_struct/rbs.rb +151 -271
  26. data/lib/field_struct/registered_option.rb +113 -0
  27. data/lib/field_struct/registry.rb +40 -50
  28. data/lib/field_struct/restrictions.rb +90 -0
  29. data/lib/field_struct/scaffold.rb +274 -301
  30. data/lib/field_struct/suggestion.rb +33 -0
  31. data/lib/field_struct/types/array.rb +147 -126
  32. data/lib/field_struct/types/base.rb +113 -124
  33. data/lib/field_struct/types/big_decimal.rb +59 -55
  34. data/lib/field_struct/types/binary.rb +18 -25
  35. data/lib/field_struct/types/boolean.rb +74 -97
  36. data/lib/field_struct/types/builtin.rb +32 -0
  37. data/lib/field_struct/types/date.rb +23 -137
  38. data/lib/field_struct/types/datetime.rb +30 -139
  39. data/lib/field_struct/types/element_options.rb +51 -0
  40. data/lib/field_struct/types/email.rb +27 -38
  41. data/lib/field_struct/types/float.rb +58 -56
  42. data/lib/field_struct/types/format_presets.rb +30 -0
  43. data/lib/field_struct/types/hash.rb +144 -0
  44. data/lib/field_struct/types/immutable_string.rb +16 -9
  45. data/lib/field_struct/types/integer.rb +74 -102
  46. data/lib/field_struct/types/nested.rb +57 -58
  47. data/lib/field_struct/types/preset_resolver.rb +9 -24
  48. data/lib/field_struct/types/rfc3339_format.rb +70 -153
  49. data/lib/field_struct/types/string.rb +48 -46
  50. data/lib/field_struct/types/symbol.rb +23 -20
  51. data/lib/field_struct/types/temporal.rb +232 -0
  52. data/lib/field_struct/types/time.rb +32 -145
  53. data/lib/field_struct/types/union.rb +111 -65
  54. data/lib/field_struct/types/union_pick.rb +139 -0
  55. data/lib/field_struct/types/url.rb +24 -35
  56. data/lib/field_struct/types/uuid.rb +24 -35
  57. data/lib/field_struct/types/value.rb +14 -9
  58. data/lib/field_struct/types/zone.rb +118 -0
  59. data/lib/field_struct/version.rb +3 -3
  60. data/lib/field_struct.rb +102 -122
  61. data/sig/field_struct.rbs +1180 -2300
  62. data/sig/manifest.yaml +6 -0
  63. data/skills/field-struct/SKILL.md +73 -159
  64. metadata +37 -28
  65. data/CODE_OF_CONDUCT.md +0 -132
  66. data/UPGRADING.md +0 -743
  67. data/lib/field_struct/error.rb +0 -48
  68. data/lib/field_struct/types/temporal_parser.rb +0 -93
  69. data/lib/field_struct/types/time_format_resolver.rb +0 -54
  70. data/lib/field_struct/types/zone_option.rb +0 -267
@@ -1,299 +1,179 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module FieldStruct
4
- # Generates RBS type signatures for the *generated* instance surface of
5
- # user-defined {FieldStruct::Base} subclasses — the per-field accessors the
6
- # +field+ DSL defines dynamically.
7
- #
8
- # Sord generates +sig/field_struct.rbs+ from the library's static source, so
9
- # it covers {Base}, {Types}, {Registry}, … but it can never see +User#name+
10
- # or +User#age=+: those methods don't exist until a consumer declares the
11
- # fields. This is the deferred "track 2" of the plan's RBS strategy (D13) —
12
- # walk a subclass's {Metadata} and emit signatures for its accessors so
13
- # downstream Steep / Solargraph can type-check code that touches them.
14
- #
15
- # class User < FieldStruct::Base
16
- # required :name, :string
17
- # optional :age, :integer
18
- # end
19
- #
20
- # puts FieldStruct::RBS.generate(User)
21
- # # # Generated by FieldStruct::RBS. ...
22
- # # class User < ::FieldStruct::Base
23
- # # attr_reader name: ::String
24
- # # def name=: (::String? value) -> ::String?
25
- # #
26
- # # attr_reader age: ::Integer?
27
- # # def age=: (::Integer? value) -> ::Integer?
28
- # # end
29
- #
30
- # Design choices:
31
- #
32
- # * **Types describe a valid instance.** The reader type is the field's
33
- # {Types::Base#ruby_type} (or an override, below). Nullability follows
34
- # {Field#required?}: required → +T+, optional → +T?+. An invalid
35
- # instance — a required field left unset, or a +:keep_raw+ coercion
36
- # failure holding the raw input — can hold other values; check +valid?+
37
- # before trusting the signature. The generated header says so.
38
- # * **Writer** is +(T? value) -> T?+: the runtime setter accepts +nil+ and
39
- # returns the coerced value. Loose input the type would coerce
40
- # (+user.age = "30"+) is valid Ruby but a type error to Steep — cast or
41
- # coerce at the boundary.
42
- # * **Generic arguments** are filled in: arrays as +::Array[Element]+
43
- # (a scalar element as +Element?+, since a valid instance can hold nil
44
- # elements; a nested element stays non-nil, since nil makes it invalid),
45
- # unions as +(A | B)+ (a boolean member as +bool+, a member's own
46
- # {Types::Base#rbs_type} first), nested structs by qualified name; an
47
- # anonymous nested class raises +ArgumentError+. A custom type whose +ruby_type+ is a bare generic
48
- # class (+::Hash+) gets +untyped+ arguments unless it declares
49
- # {Types::Base#rbs_type}.
50
- # * **Anything-valued fields** (+:value+, or a union with a +:value+
51
- # member) are +untyped+ — reader and writer, never +untyped?+.
52
- # * **Overrides:** a field's +rbs_type:+ option, then the type's
53
- # {Types::Base#rbs_type}, replace the derived type +T+ verbatim;
54
- # nullability is still added for optional fields and writers.
55
- # * **+new+ / +initialize+** are inherited from {Base}, which already
56
- # accepts +User.new(name: ...)+.
57
- #
58
- # Each call emits one class. Referenced types (nested structs, array
59
- # elements) appear as qualified names (+::Address+) — generate RBS for those
60
- # classes too so the references resolve. {.type_for} exposes the per-field
61
- # mapping for other generators.
4
+ # Writes RBS for classes that inherit FieldStruct::Base (FS-B127 to FS-B130). The types describe a valid
5
+ # instance, so a required field's reader has no +?+ and every writer accepts +nil+.
62
6
  module RBS
63
- # The pair a +:boolean+ field's +ruby_type+ returns, rendered as +bool+.
64
- # @return [Array<Class>]
65
- BOOL_CLASSES = [TrueClass, FalseClass].freeze
66
- private_constant :BOOL_CLASSES
67
-
68
- # Comment lines opening every {.generate} result: the contract the
69
- # signatures hold to.
70
- # @return [String]
71
- HEADER = <<~RBS
7
+ # The comment header every generated signature starts with.
8
+ # @return [::String]
9
+ HEADER = <<~TEXT
72
10
  # Generated by FieldStruct::RBS. Types describe a valid instance: an
73
11
  # invalid one (a required field left unset, or a :keep_raw coercion
74
12
  # failure holding the raw input) can hold other values. Check valid?.
75
- RBS
76
- private_constant :HEADER
77
-
78
- # Ruby classes RBS declares with type parameters, and how many. A bare
79
- # +ruby_type+ naming one of these is emitted with +untyped+ arguments,
80
- # since RBS rejects a generic class without them.
81
- # @return [Hash{Class=>Integer}]
82
- GENERIC_ARITY = {::Array => 1, ::Hash => 2, ::Range => 1}.freeze
83
- private_constant :GENERIC_ARITY
84
-
85
- # Generate RBS source for a single FieldStruct subclass.
86
- #
87
- # @param klass [Class<FieldStruct::Base>]
88
- # @return [String] RBS declaring the class (wrapped in its module nesting)
89
- # and a typed reader and writer for every field it declares, after a
90
- # comment header stating that the types describe a valid instance
91
- # @raise [ArgumentError] when +klass+ is not a named {FieldStruct::Base}
92
- # subclass
93
- def self.generate(klass)
94
- unless klass.is_a?(::Class) && klass < FieldStruct::Base
95
- raise ArgumentError,
96
- "FieldStruct::RBS.generate expects a FieldStruct::Base subclass, got #{klass.inspect}"
13
+ TEXT
14
+
15
+ GENERIC_ARGUMENTS = { ::Array => '::Array[untyped]', ::Hash => '::Hash[untyped, untyped]', ::Range => '::Range[untyped]' }.freeze
16
+ SCALARS = {
17
+ ::String => '::String', ::Symbol => '::Symbol', ::Integer => '::Integer', ::Float => '::Float', ::BigDecimal => '::BigDecimal',
18
+ ::Date => '::Date', ::Time => '::Time', ::DateTime => '::DateTime'
19
+ }.freeze
20
+ OPERATORS = /[|&^]/
21
+ private_constant :GENERIC_ARGUMENTS, :SCALARS, :OPERATORS
22
+
23
+ class << self
24
+ # Builds the signature text for one class: a comment header, then the class inside +module+ blocks for its namespace.
25
+ #
26
+ # @param klass [Class] a strict subclass of +FieldStruct::Base+ with a name
27
+ # @return [String] RBS source ending in a newline
28
+ # @raise [ArgumentError] for anything else, or an anonymous class
29
+ def generate(klass)
30
+ unless klass.is_a?(::Class) && klass < FieldStruct::Base
31
+ raise ::ArgumentError, "FieldStruct::RBS.generate expects a FieldStruct::Base subclass, got #{klass.inspect}"
32
+ end
33
+ raise ::ArgumentError, 'cannot generate RBS for an anonymous class' if klass.name.nil?
34
+
35
+ segments = klass.name.split('::')
36
+ body = class_lines(klass, segments.last)
37
+ wrapped = segments[0...-1].each_with_index.reverse_each.reduce(body) do |lines, (segment, depth)|
38
+ wrap(lines, segment, namespace_keyword(segments[0..depth]))
39
+ end
40
+ "#{HEADER}#{wrapped.join("\n")}\n"
97
41
  end
98
- raise ArgumentError, 'cannot generate RBS for an anonymous class' unless klass.name
99
42
 
100
- HEADER + wrap_namespace(klass.name, class_block(klass))
101
- end
43
+ # The RBS type of one field's reader (or writer).
44
+ #
45
+ # @param field [FieldStruct::Field]
46
+ # @param nullable [Boolean, nil] +nil+ means nullable unless the field is required
47
+ # @return [String]
48
+ # @raise [ArgumentError] for a non-Field, or a reference to an anonymous class
49
+ def type_for(field, nullable: nil)
50
+ unless field.is_a?(FieldStruct::Field)
51
+ raise ::ArgumentError, "FieldStruct::RBS.type_for expects a FieldStruct::Field (e.g. User.metadata[:name]), got #{field.inspect}"
52
+ end
53
+
54
+ nullable = !field.required? || field.nullable? if nullable.nil?
55
+ base = field.rbs_type ? normalize(field.rbs_type) : derive(field.type_instance, field.options)
56
+ nullable ? nullify(base) : base
57
+ end
58
+
59
+ private
102
60
 
103
- # The RBS type of one field's value, as {.generate} emits it — for other
104
- # generators (e.g. one typing a method that takes or returns the field)
105
- # that need the same mapping:
106
- #
107
- # FieldStruct::RBS.type_for(Order.metadata[:items])
108
- # # => "::Array[::LineItem]?"
109
- # FieldStruct::RBS.type_for(Order.metadata[:items], nullable: false)
110
- # # => "::Array[::LineItem]"
111
- #
112
- # The type comes from the field's +rbs_type:+ option, else its type's
113
- # {Types::Base#rbs_type}, else its {Types::Base#ruby_type} with generic
114
- # arguments filled in. Qualified names (+::LineItem+) assume the
115
- # referenced classes get RBS too.
116
- #
117
- # @param field [Field] a declared field, e.g. +Order.metadata[:items]+
118
- # @param nullable [Boolean, nil] append +?+ (the reader type of an
119
- # optional field, and every writer's); +nil+, the default, means
120
- # +!field.required?+. Never applied to +untyped+, which already
121
- # admits +nil+.
122
- # @return [String] an RBS type expression
123
- # @raise [ArgumentError] when +field+ is not a {Field}
124
- def self.type_for(field, nullable: nil)
125
- unless field.is_a?(FieldStruct::Field)
126
- raise ArgumentError, 'FieldStruct::RBS.type_for expects a FieldStruct::Field ' \
127
- "(e.g. User.metadata[:name]), got #{field.inspect}"
61
+ def class_lines(klass, short_name)
62
+ parent = klass.superclass
63
+ raise ::ArgumentError, 'cannot generate RBS for an anonymous class' if parent.name.nil?
64
+
65
+ lines = ["class #{short_name} < ::#{parent.name}"]
66
+ entries = own_fields(klass, parent).map { |field| field_lines(field) }
67
+ lines.concat(entries.flat_map.with_index { |entry, index| index.zero? ? entry : ['', *entry] })
68
+ lines << 'end'
128
69
  end
129
70
 
130
- nullable = !field.required? if nullable.nil?
131
- base = override_expression(field.rbs_type || field.type_instance.rbs_type) ||
132
- expression_for(field.type_instance, field.options)
133
- nullable ? optional(base) : base
134
- end
71
+ def own_fields(klass, parent)
72
+ inherited = parent < FieldStruct::Base ? parent.metadata : nil
73
+ klass.metadata.reject { |field| inherited && inherited[field.name].equal?(field) }
74
+ end
135
75
 
136
- # Build the +class ... end+ block (unindented, no surrounding modules).
137
- #
138
- # @param klass [Class<FieldStruct::Base>]
139
- # @return [String]
140
- def self.class_block(klass)
141
- simple = klass.name.split('::').last
142
- lines = ["class #{simple} < ::#{klass.superclass.name}"]
143
- own_fields(klass).each_with_index do |field, index|
76
+ def field_lines(field)
144
77
  writer = type_for(field, nullable: true)
145
- lines << '' unless index.zero?
146
- lines << " attr_reader #{field.name}: #{type_for(field)}"
147
- lines << " def #{field.name}=: (#{writer} value) -> #{writer}"
78
+ [" attr_reader #{field.name}: #{type_for(field)}", " def #{field.name}=: (#{writer} value) -> #{writer}"]
148
79
  end
149
- lines << 'end'
150
- lines.join("\n")
151
- end
152
- private_class_method :class_block
153
-
154
- # Fields declared on +klass+ itself — inherited fields (the same {Field}
155
- # objects merged in at inheritance time) belong to the parent's RBS.
156
- #
157
- # @param klass [Class<FieldStruct::Base>]
158
- # @return [Array<Field>]
159
- def self.own_fields(klass)
160
- parent = klass.superclass
161
- parent_meta = parent.respond_to?(:metadata) ? parent.metadata : nil
162
- klass.metadata.reject { |field| parent_meta && parent_meta[field.name].equal?(field) }
163
- end
164
- private_class_method :own_fields
165
80
 
166
- # An override, parenthesized when it is a union, intersection or proc
167
- # type, so a trailing +?+ applies to the whole of it.
168
- #
169
- # @param rbs [String, nil] a field's +rbs_type:+ or a type's +rbs_type+
170
- # @return [String, nil] +nil+ when there is no override
171
- def self.override_expression(rbs)
172
- return nil if rbs.nil?
81
+ def wrap(lines, segment, keyword)
82
+ ["#{keyword} #{segment}", *lines.map { |line| line.empty? ? line : " #{line}" }, 'end']
83
+ end
173
84
 
174
- rbs = rbs.strip
175
- return rbs if wrapped?(rbs)
85
+ def namespace_keyword(path)
86
+ Object.const_get(path.join('::')).is_a?(::Class) ? 'class' : 'module'
87
+ rescue ::NameError
88
+ 'module'
89
+ end
176
90
 
177
- rbs.match?(/[|&^]/) ? "(#{rbs})" : rbs
178
- end
179
- private_class_method :override_expression
180
-
181
- # @param rbs [String] a stripped RBS type expression
182
- # @return [Boolean] whether one parenthesized group spans all of +rbs+
183
- # (optionally followed by +?+), so wrapping it again adds nothing
184
- def self.wrapped?(rbs)
185
- return false unless rbs.start_with?('(')
186
-
187
- depth = 0
188
- rbs.each_char.with_index do |char, index|
189
- depth += 1 if char == '('
190
- depth -= 1 if char == ')'
191
- return rbs[(index + 1)..].then { |rest| rest.empty? || rest == '?' } if depth.zero?
91
+ def derive(type, options = {})
92
+ override = type.rbs_type
93
+ return normalize(override) if override
94
+
95
+ case type
96
+ when Types::Nested then class_name(type.struct_class)
97
+ when Types::Array then array_type(options[:of_type])
98
+ when Types::Hash then hash_type(options[:of_type])
99
+ when Types::Union then union_type(type)
100
+ else ruby_types(type.ruby_type)
101
+ end
192
102
  end
193
- false
194
- end
195
- private_class_method :wrapped?
196
103
 
197
- # @param base [String] an RBS type expression
198
- # @return [String] +base+ made nullable, unless it already admits +nil+
199
- def self.optional(base)
200
- return base if base == 'untyped' || base.end_with?('?')
104
+ def array_type(of_type)
105
+ return '::Array[untyped]' if of_type.nil?
201
106
 
202
- "#{base}?"
203
- end
204
- private_class_method :optional
205
-
206
- # Map a type instance (plus its field options, needed for arrays) to an
207
- # RBS type expression.
208
- #
209
- # @param type_instance [Types::Base]
210
- # @param options [Hash{Symbol=>Object, nil}]
211
- # @return [String]
212
- def self.expression_for(type_instance, options)
213
- return "::Array[#{element_type(options[:of_type])}]" if type_instance.is_a?(FieldStruct::Types::Array)
214
- return union_expression(type_instance) if type_instance.is_a?(FieldStruct::Types::Union)
215
-
216
- ruby_type = type_instance.ruby_type
217
- classes = ruby_type.is_a?(::Array) ? ruby_type : [ruby_type]
218
- mapped = classes_to_rbs(classes)
219
- return 'untyped' if mapped.include?('untyped')
220
-
221
- mapped.one? ? mapped.first : "(#{mapped.join(" | ")})"
222
- end
223
- private_class_method :expression_for
224
-
225
- # A union as its members' types, each member's own +rbs_type+ first.
226
- #
227
- # @param union [Types::Union]
228
- # @return [String] +untyped+ when any member is
229
- def self.union_expression(union)
230
- members = union.member_types.map { |member| override_expression(member.rbs_type) || expression_for(member, {}) }
231
- return 'untyped' if members.include?('untyped')
232
-
233
- members = members.uniq
234
- members.one? ? members.first : "(#{members.join(" | ")})"
235
- end
236
- private_class_method :union_expression
237
-
238
- # @param classes [Array<Class>] a {Types::Base#ruby_type}, as a list
239
- # @return [Array<String>] one RBS type per class, with +TrueClass+ /
240
- # +FalseClass+ together collapsed to +bool+ where the pair appears
241
- def self.classes_to_rbs(classes)
242
- bool = BOOL_CLASSES.all? { |klass| classes.include?(klass) }
243
- classes.map { |klass| bool && BOOL_CLASSES.include?(klass) ? 'bool' : class_to_rbs(klass) }.uniq
244
- end
245
- private_class_method :classes_to_rbs
246
-
247
- # The element type of an array field, derived from its +:of_type+ (a
248
- # +Types::Base+ subclass for stock types, or a built instance for
249
- # parameterized ones like {Types::Nested}).
250
- #
251
- # @param of_type [Class, Types::Base, nil]
252
- # @return [String]
253
- def self.element_type(of_type)
254
- return 'untyped' if of_type.nil?
255
-
256
- instance = of_type.is_a?(::Class) ? of_type.new : of_type
257
- expression = override_expression(instance.rbs_type) || expression_for(instance, {})
258
- # A valid instance may hold nil scalar elements; a nil nested element
259
- # fails validation, so nested elements stay non-nil.
260
- instance.is_a?(FieldStruct::Types::Nested) ? expression : optional(expression)
261
- end
262
- private_class_method :element_type
107
+ element = of_type.is_a?(::Class) ? of_type.new : of_type
108
+ inner = derive(element)
109
+ inner = nullify(inner) unless element.is_a?(Types::Nested)
110
+ "::Array[#{inner}]"
111
+ end
263
112
 
264
- # @param klass [Class] a Ruby class from a {Types::Base#ruby_type}
265
- # @return [String] qualified RBS name (with +untyped+ type arguments for
266
- # a generic class), or +untyped+ for the value type's +::Object+
267
- def self.class_to_rbs(klass)
268
- return 'untyped' if klass == ::Object
269
- raise ArgumentError, 'FieldStruct::RBS cannot name an anonymous class; assign it to a constant' if klass.name.nil?
113
+ def hash_type(of_type)
114
+ return '::Hash[::String, untyped]' if of_type.nil?
270
115
 
271
- arity = GENERIC_ARITY[klass]
272
- return "::#{klass.name}" unless arity
116
+ "::Hash[::String, #{array_type(of_type).delete_prefix('::Array[').delete_suffix(']')}]"
117
+ end
273
118
 
274
- "::#{klass.name}[#{Array.new(arity, "untyped").join(", ")}]"
275
- end
276
- private_class_method :class_to_rbs
277
-
278
- # Wrap an inner block in the +module ... end+ nesting implied by a
279
- # qualified class name, indenting two spaces per level.
280
- #
281
- # @param full_name [String] e.g. +"Acme::Order"+
282
- # @param inner [String] the class block
283
- # @return [String] RBS source ending in a trailing newline
284
- def self.wrap_namespace(full_name, inner)
285
- modules = full_name.split('::')[0...-1]
286
- block = inner
287
- modules.reverse_each { |mod| block = "module #{mod}\n#{indent(block)}\nend" }
288
- "#{block}\n"
289
- end
290
- private_class_method :wrap_namespace
119
+ def union_type(union)
120
+ members = union.member_types.map { |member| derive(member) }.uniq
121
+ return 'untyped' if members.empty? || members.include?('untyped')
291
122
 
292
- # @param text [String]
293
- # @return [String] +text+ with every non-blank line indented two spaces
294
- def self.indent(text)
295
- text.split("\n", -1).map { |line| line.empty? ? line : " #{line}" }.join("\n")
123
+ members.size == 1 ? members.first : "(#{members.join(' | ')})"
124
+ end
125
+
126
+ def ruby_types(classes)
127
+ names = [classes].flatten.map { |klass| class_type(klass) }.uniq
128
+ names = collapse_booleans(names)
129
+ return 'untyped' if names.include?('untyped')
130
+
131
+ names.size == 1 ? names.first : "(#{names.join(' | ')})"
132
+ end
133
+
134
+ def collapse_booleans(names)
135
+ return names unless names.include?('::TrueClass') && names.include?('::FalseClass')
136
+
137
+ position = names.index('::TrueClass')
138
+ (names - %w[::TrueClass ::FalseClass]).insert(position, 'bool')
139
+ end
140
+
141
+ def class_type(klass)
142
+ return 'untyped' if klass == ::Object
143
+ return SCALARS[klass] if SCALARS.key?(klass)
144
+ return GENERIC_ARGUMENTS[klass] if GENERIC_ARGUMENTS.key?(klass)
145
+
146
+ class_name(klass)
147
+ end
148
+
149
+ def class_name(klass)
150
+ raise ::ArgumentError, 'FieldStruct::RBS cannot name an anonymous class; assign it to a constant' if klass.name.nil?
151
+
152
+ "::#{klass.name}"
153
+ end
154
+
155
+ # Strips an override and parenthesizes it when it holds an operator outside one wrapped group.
156
+ def normalize(text)
157
+ text = text.strip
158
+ return text unless text.match?(OPERATORS)
159
+
160
+ one_group?(text.delete_suffix('?')) ? text : "(#{text})"
161
+ end
162
+
163
+ def one_group?(text)
164
+ return false unless text.start_with?('(') && text.end_with?(')')
165
+
166
+ depth = 0
167
+ text.each_char.with_index do |char, index|
168
+ depth += { '(' => 1, ')' => -1 }.fetch(char, 0)
169
+ return false if depth.zero? && index < text.length - 1
170
+ end
171
+ true
172
+ end
173
+
174
+ def nullify(type)
175
+ type == 'untyped' || type.end_with?('?') ? type : "#{type}?"
176
+ end
296
177
  end
297
- private_class_method :indent
298
178
  end
299
179
  end
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ # A field option an adapter or app registered with {FieldStruct.register_option}.
5
+ class RegisteredOption
6
+ # @return [Symbol] the option key, e.g. +:avro+
7
+ attr_reader :name
8
+
9
+ # @return [Array<Class>] the classes a declared value may be an instance of
10
+ attr_reader :type
11
+
12
+ # @return [String] the gem or app that reads the option
13
+ attr_reader :owner
14
+
15
+ # @param name [Symbol]
16
+ # @param type [Array<Class>]
17
+ # @param owner [String]
18
+ def initialize(name, type, owner)
19
+ @name = name
20
+ @type = type.dup.freeze
21
+ @owner = owner.dup.freeze
22
+ freeze
23
+ end
24
+ end
25
+
26
+ # Holds the registered field options and checks registrations (FS-B10a).
27
+ # @api private
28
+ module OptionRegistry
29
+ # The keys the adapters in this repo register, so the error for one used before its adapter loads can say which
30
+ # file to require. Nothing is loaded from here.
31
+ # @return [::Hash{::Symbol=>::Array<::String>}] key to [gem name, require path]
32
+ ADAPTER_KEYS = {
33
+ avro: %w[field_struct-avro field_struct/avro],
34
+ proto: %w[field_struct-protobuf field_struct/protobuf],
35
+ json_schema: %w[field_struct-json_schema field_struct/json_schema]
36
+ }.freeze
37
+
38
+ @entries = {}.freeze
39
+
40
+ class << self
41
+ # @return [Hash{Symbol=>FieldStruct::RegisteredOption}] frozen, in registration order
42
+ attr_reader :entries
43
+
44
+ # @param name [Symbol]
45
+ # @param type [Class, Array<Class>]
46
+ # @param owner [String]
47
+ # @return [Symbol] +name+
48
+ # @raise [ArgumentError] for a bad argument, a universal or built-in native key, or a changed registration
49
+ def register(name, type, owner)
50
+ classes = check_arguments(name, type, owner)
51
+ existing = @entries[name]
52
+ return name if existing && existing.type == classes && existing.owner == owner
53
+
54
+ refuse_existing(existing) if existing
55
+ refuse_core(name)
56
+ @entries = @entries.merge(name => RegisteredOption.new(name, classes, owner)).freeze
57
+ name
58
+ end
59
+
60
+ # The message for a key nobody declares or registered.
61
+ #
62
+ # @param key [Symbol]
63
+ # @param label [String] +Class#field+ or +field :name+
64
+ # @param native [Array<Symbol>] the field type's own option keys
65
+ # @return [String]
66
+ def unknown_message(key, label, native)
67
+ adapter = ADAPTER_KEYS[key]
68
+ if adapter
69
+ return "unknown option #{key}: on #{label}; #{key}: is registered by #{adapter[0]}, " \
70
+ "so require '#{adapter[1]}' before declaring the field"
71
+ end
72
+
73
+ candidates = native + FieldBuilder::UNIVERSAL_OPTIONS + @entries.keys + ADAPTER_KEYS.keys
74
+ "unknown option #{key}: on #{label}#{Suggestion.clause(key, candidates, sigil: '', suffix: ':')}"
75
+ end
76
+
77
+ private
78
+
79
+ def check_arguments(name, type, owner)
80
+ unless name.is_a?(::Symbol)
81
+ raise ::ArgumentError, "register_option takes the option name as a Symbol, got #{name.class} (#{name.inspect})"
82
+ end
83
+
84
+ classes = Array(type)
85
+ if classes.empty? || !classes.all?(::Class)
86
+ raise ::ArgumentError, "register_option type: must be a Class or an Array of Classes, got #{type.inspect}"
87
+ end
88
+ unless owner.is_a?(::String) && !owner.strip.empty?
89
+ raise ::ArgumentError, "register_option owner: must name the gem or app that reads the option, got #{owner.inspect}"
90
+ end
91
+
92
+ classes
93
+ end
94
+
95
+ def refuse_existing(existing)
96
+ raise ::ArgumentError, "#{existing.name}: is already registered by #{existing.owner} " \
97
+ "(type #{existing.type.map { |klass| OptionChecker.short(klass) }.join(' or ')}); " \
98
+ 'register it again only with the same type: and owner:'
99
+ end
100
+
101
+ def refuse_core(name)
102
+ if FieldBuilder::UNIVERSAL_OPTIONS.include?(name)
103
+ raise ::ArgumentError, "#{name}: is a universal field option, so it can't be registered"
104
+ end
105
+
106
+ owners = FieldStruct.types.type_classes.select { |klass| klass.option_schema.key?(name) }
107
+ return if owners.empty?
108
+
109
+ raise ::ArgumentError, "#{name}: is a native option of #{owners.map(&:short_name).join(', ')}, so it can't be registered"
110
+ end
111
+ end
112
+ end
113
+ end