panko_serializer 0.8.5 → 1.0.1

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 (78) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +6 -4
  3. data/lib/panko/array_serializer.rb +55 -16
  4. data/lib/panko/code_gen/active_record/access_classifier.rb +65 -0
  5. data/lib/panko/code_gen/code_builder.rb +32 -0
  6. data/lib/panko/code_gen/compiler.rb +61 -0
  7. data/lib/panko/code_gen/config.rb +75 -0
  8. data/lib/panko/code_gen/datetime_format.rb +38 -0
  9. data/lib/panko/code_gen/descriptor.rb +138 -0
  10. data/lib/panko/code_gen/descriptor_builder.rb +166 -0
  11. data/lib/panko/code_gen/dump.rb +49 -0
  12. data/lib/panko/code_gen/errors.rb +21 -0
  13. data/lib/panko/code_gen/filter.rb +29 -0
  14. data/lib/panko/code_gen/filter_adapter.rb +44 -0
  15. data/lib/panko/code_gen/filters/indexed.rb +62 -0
  16. data/lib/panko/code_gen/filters/none.rb +19 -0
  17. data/lib/panko/code_gen/generator.rb +23 -0
  18. data/lib/panko/code_gen/generators/banner.rb +27 -0
  19. data/lib/panko/code_gen/generators/class_emitter.rb +120 -0
  20. data/lib/panko/code_gen/generators/cycle_membership.rb +53 -0
  21. data/lib/panko/code_gen/generators/descriptor_walk.rb +22 -0
  22. data/lib/panko/code_gen/generators/fanout.rb +60 -0
  23. data/lib/panko/code_gen/generators/field_index.rb +29 -0
  24. data/lib/panko/code_gen/generators/field_walk.rb +38 -0
  25. data/lib/panko/code_gen/generators/generated_names.rb +93 -0
  26. data/lib/panko/code_gen/generators/hash_sink.rb +217 -0
  27. data/lib/panko/code_gen/generators/json_sink.rb +286 -0
  28. data/lib/panko/code_gen/generators/record_access/generic.rb +92 -0
  29. data/lib/panko/code_gen/generators/record_access/specialized.rb +92 -0
  30. data/lib/panko/code_gen/generators/release.rb +60 -0
  31. data/lib/panko/code_gen/generators/sink.rb +80 -0
  32. data/lib/panko/code_gen/instance_pool.rb +27 -0
  33. data/lib/panko/code_gen/runtime.rb +27 -0
  34. data/lib/panko/code_gen/serializer_cache.rb +242 -0
  35. data/lib/panko/code_gen/validators/callable_arity.rb +42 -0
  36. data/lib/panko/code_gen/validators/name_uniqueness.rb +44 -0
  37. data/lib/panko/code_gen/validators/source_resolution.rb +48 -0
  38. data/lib/panko/code_gen/validators/validator.rb +15 -0
  39. data/lib/panko/code_gen/writers_pool.rb +51 -0
  40. data/lib/panko/code_gen.rb +80 -0
  41. data/lib/panko/compile_all.rb +80 -0
  42. data/lib/panko/compile_all_result.rb +21 -0
  43. data/lib/panko/config.rb +71 -0
  44. data/lib/panko/descriptor.rb +93 -0
  45. data/lib/panko/response.rb +40 -8
  46. data/lib/panko/serializer.rb +176 -91
  47. data/lib/panko/serializer_resolver.rb +2 -8
  48. data/lib/panko/version.rb +1 -1
  49. data/lib/panko_serializer.rb +3 -5
  50. metadata +47 -35
  51. data/ext/panko_serializer/attributes_writer/active_record.c +0 -181
  52. data/ext/panko_serializer/attributes_writer/active_record.h +0 -17
  53. data/ext/panko_serializer/attributes_writer/attributes_writer.c +0 -55
  54. data/ext/panko_serializer/attributes_writer/attributes_writer.h +0 -35
  55. data/ext/panko_serializer/attributes_writer/common.c +0 -10
  56. data/ext/panko_serializer/attributes_writer/common.h +0 -9
  57. data/ext/panko_serializer/attributes_writer/hash.c +0 -13
  58. data/ext/panko_serializer/attributes_writer/hash.h +0 -7
  59. data/ext/panko_serializer/attributes_writer/plain.c +0 -13
  60. data/ext/panko_serializer/attributes_writer/plain.h +0 -7
  61. data/ext/panko_serializer/attributes_writer/type_cast/time_conversion.c +0 -156
  62. data/ext/panko_serializer/attributes_writer/type_cast/time_conversion.h +0 -10
  63. data/ext/panko_serializer/attributes_writer/type_cast/type_cast.c +0 -409
  64. data/ext/panko_serializer/attributes_writer/type_cast/type_cast.h +0 -81
  65. data/ext/panko_serializer/common.h +0 -9
  66. data/ext/panko_serializer/extconf.rb +0 -28
  67. data/ext/panko_serializer/panko_serializer.c +0 -181
  68. data/ext/panko_serializer/panko_serializer.h +0 -12
  69. data/ext/panko_serializer/serialization_descriptor/association.c +0 -90
  70. data/ext/panko_serializer/serialization_descriptor/association.h +0 -20
  71. data/ext/panko_serializer/serialization_descriptor/attribute.c +0 -96
  72. data/ext/panko_serializer/serialization_descriptor/attribute.h +0 -27
  73. data/ext/panko_serializer/serialization_descriptor/serialization_descriptor.c +0 -177
  74. data/ext/panko_serializer/serialization_descriptor/serialization_descriptor.h +0 -30
  75. data/lib/panko/association.rb +0 -17
  76. data/lib/panko/attribute.rb +0 -29
  77. data/lib/panko/object_writer.rb +0 -68
  78. data/lib/panko/serialization_descriptor.rb +0 -180
@@ -0,0 +1,286 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Panko::CodeGen
4
+ module Generators
5
+ class JsonSink < Sink
6
+ def output
7
+ :json
8
+ end
9
+
10
+ def suffix
11
+ "JSON"
12
+ end
13
+
14
+ def entry_name
15
+ GeneratedNames.write_one
16
+ end
17
+
18
+ def generic_entry_name
19
+ GeneratedNames.generic_write_one
20
+ end
21
+
22
+ def split_hash_helper
23
+ GeneratedNames.write_one_hash
24
+ end
25
+
26
+ def split_object_helper
27
+ GeneratedNames.write_one_object
28
+ end
29
+
30
+ def entry_params
31
+ "record, writer, context, scope, filters"
32
+ end
33
+
34
+ def emit_class_constants(descriptor, config, builder)
35
+ subclass = defined?(ActiveSupport::IsolatedExecutionState) ? "IsolatedExecutionState" : "ThreadLocal"
36
+ builder.line "POOL = Panko::CodeGen::WritersPool::#{subclass}.new"
37
+ end
38
+
39
+ def emit_serialize_one(config, builder)
40
+ signature = config.supports_root_key ?
41
+ "def serialize_one(record, context: nil, scope: nil, filters: nil, root_key: nil)" :
42
+ "def serialize_one(record, context: nil, scope: nil, filters: nil)"
43
+ builder.line signature
44
+ builder.indent do
45
+ builder.line "filters = Panko::CodeGen::Filter.wrap(filters, #{GeneratedNames.field_index_const})"
46
+ if config.supports_root_key
47
+ builder.line "validate_root_key!(root_key)"
48
+ end
49
+ with_writer(builder) { emit_serialize_one_body(config, builder) }
50
+ end
51
+ builder.line "end"
52
+ end
53
+
54
+ def emit_serialize_many(config, builder)
55
+ signature = config.supports_root_key ?
56
+ "def serialize_many(records, context: nil, scope: nil, filters: nil, root_key: nil)" :
57
+ "def serialize_many(records, context: nil, scope: nil, filters: nil)"
58
+ builder.line signature
59
+ builder.indent do
60
+ builder.line "filters = Panko::CodeGen::Filter.wrap(filters, #{GeneratedNames.field_index_const})"
61
+ if config.supports_root_key
62
+ builder.line "validate_root_key!(root_key)"
63
+ end
64
+ with_writer(builder) { emit_serialize_many_body(config, builder) }
65
+ end
66
+ builder.line "end"
67
+ end
68
+
69
+ # Write into a writer the caller owns, so a JSON document that holds this output
70
+ # (Panko::Response) gets it without a String copy. No pooled writer, no root key.
71
+ def emit_serialize_to(config, builder)
72
+ builder.line "def serialize_one_to(writer, record, key = nil, context: nil, scope: nil, filters: nil)"
73
+ builder.indent do
74
+ builder.line "filters = Panko::CodeGen::Filter.wrap(filters, #{GeneratedNames.field_index_const})"
75
+ builder.line "writer.push_key(key) if key"
76
+ builder.line "#{GeneratedNames.write_one}(record, writer, context, scope, filters)"
77
+ builder.line "nil"
78
+ end
79
+ builder.line "end"
80
+ builder.blank
81
+ builder.line "def serialize_many_to(writer, records, key = nil, context: nil, scope: nil, filters: nil)"
82
+ builder.indent do
83
+ builder.line "filters = Panko::CodeGen::Filter.wrap(filters, #{GeneratedNames.field_index_const})"
84
+ builder.line "writer.push_array(key)"
85
+ builder.line "records.each { |r| #{GeneratedNames.write_one}(r, writer, context, scope, filters) }"
86
+ builder.line "writer.pop"
87
+ builder.line "nil"
88
+ end
89
+ builder.line "end"
90
+ end
91
+
92
+ def open_record(builder)
93
+ builder.line "writer.push_object"
94
+ end
95
+
96
+ def close_record(builder)
97
+ builder.line "writer.pop"
98
+ end
99
+
100
+ # +cast:+ exists to match {HashSink#attribute} and is ignored: Oj's +:rails+ mode formats
101
+ # JSON values.
102
+ def attribute(attribute, read_expr, config, index, builder, cast: true)
103
+ builder.line "unless filters.drops?(#{index})"
104
+ builder.indent do
105
+ builder.line "writer.push_value(#{read_expr}, #{GeneratedNames.string_literal(attribute.name)})"
106
+ end
107
+ builder.line "end"
108
+ end
109
+
110
+ def specialized_attribute(attribute, ar_model, config, index, builder)
111
+ if RecordAccess::Specialized.json_column_attribute?(attribute, ar_model)
112
+ json_column_attribute(attribute, config, index, builder)
113
+ elsif RecordAccess::Specialized.datetime_column_attribute?(attribute, ar_model)
114
+ datetime_column_attribute(attribute, index, builder)
115
+ else
116
+ attribute(attribute, RecordAccess::Specialized.attribute_read_expr(attribute, ar_model), config, index, builder)
117
+ end
118
+ end
119
+
120
+ # +equal?+, not +==+, so an object that overrides +==+ cannot match +SKIP+.
121
+ def method_attribute(method_attribute, position, config, index, builder)
122
+ builder.line "unless filters.drops?(#{index})"
123
+ builder.indent do
124
+ builder.line "value = #{method_attribute_call_expression(method_attribute, position)}"
125
+ builder.line "unless value.equal?(Panko::CodeGen::SKIP)"
126
+ builder.indent do
127
+ builder.line "writer.push_value(value, #{GeneratedNames.string_literal(method_attribute.name)})"
128
+ end
129
+ builder.line "end"
130
+ end
131
+ builder.line "end"
132
+ end
133
+
134
+ def association(association, position, source_read_expr, config, index, builder)
135
+ key_lit = GeneratedNames.string_literal(association.name)
136
+ builder.line "unless filters.drops?(#{index})"
137
+ builder.indent do
138
+ with_if_guard(association, position, builder) do
139
+ case association.kind
140
+ when :has_one
141
+ builder.line "value = #{source_read_expr}"
142
+ if config.null_for_missing_has_one
143
+ has_one_default(association, position, key_lit, builder)
144
+ else
145
+ has_one_omit(association, position, key_lit, builder)
146
+ end
147
+ when :has_many
148
+ has_many(association, position, source_read_expr, key_lit, builder)
149
+ end
150
+ end
151
+ end
152
+ builder.line "end"
153
+ end
154
+
155
+ private
156
+
157
+ # +result+ starts nil so a body that raises hands checkin nil, and the writer is dropped.
158
+ def with_writer(builder, &block)
159
+ builder.line "writer = POOL.checkout"
160
+ builder.line "result = nil"
161
+ builder.line "begin"
162
+ builder.indent(&block)
163
+ builder.line "ensure"
164
+ builder.indent do
165
+ builder.line "POOL.checkin(writer, result)"
166
+ end
167
+ builder.line "end"
168
+ end
169
+
170
+ def emit_serialize_one_body(config, builder)
171
+ if config.supports_root_key
172
+ builder.line "if root_key"
173
+ builder.indent do
174
+ builder.line "writer.push_object"
175
+ builder.line "writer.push_key(root_key)"
176
+ end
177
+ builder.line "end"
178
+ end
179
+ builder.line "#{GeneratedNames.write_one}(record, writer, context, scope, filters)"
180
+ builder.line "writer.pop if root_key" if config.supports_root_key
181
+ builder.line "result = writer.to_s"
182
+ builder.line "result.chomp!"
183
+ builder.line "result"
184
+ end
185
+
186
+ def emit_serialize_many_body(config, builder)
187
+ if config.supports_root_key
188
+ builder.line "writer.push_object if root_key"
189
+ builder.line "writer.push_array(root_key)"
190
+ else
191
+ builder.line "writer.push_array"
192
+ end
193
+ builder.line "records.each { |r| #{GeneratedNames.write_one}(r, writer, context, scope, filters) }"
194
+ builder.line "writer.pop"
195
+ builder.line "writer.pop if root_key" if config.supports_root_key
196
+ builder.line "result = writer.to_s"
197
+ builder.line "result.chomp!"
198
+ builder.line "result"
199
+ end
200
+
201
+ # A non-nil +has_one+ pushes its key separately instead of +push_object("name")+: the
202
+ # child's +_write_one+ opens its own +push_object+ frame.
203
+ def has_one_default(association, position, key_lit, builder)
204
+ builder.line "if value.nil?"
205
+ builder.indent { builder.line "writer.push_value(nil, #{key_lit})" }
206
+ builder.line "else"
207
+ builder.indent do
208
+ builder.line "writer.push_key(#{key_lit})"
209
+ child_write(association, position, "value", builder) do |ivar|
210
+ "#{ivar}.#{GeneratedNames.write_one}(value, writer, context, scope, #{child_filter_expr(association)})"
211
+ end
212
+ end
213
+ builder.line "end"
214
+ end
215
+
216
+ def has_one_omit(association, position, key_lit, builder)
217
+ builder.line "unless value.nil?"
218
+ builder.indent do
219
+ builder.line "writer.push_key(#{key_lit})"
220
+ child_write(association, position, "value", builder) do |ivar|
221
+ "#{ivar}.#{GeneratedNames.write_one}(value, writer, context, scope, #{child_filter_expr(association)})"
222
+ end
223
+ end
224
+ builder.line "end"
225
+ end
226
+
227
+ def has_many(association, position, source_read_expr, key_lit, builder)
228
+ builder.line "child_filter = #{child_filter_expr(association)}"
229
+ builder.line "writer.push_array(#{key_lit})"
230
+ builder.line "#{source_read_expr}.each do |element|"
231
+ builder.indent do
232
+ child_write(association, position, "element", builder) do |ivar|
233
+ "#{ivar}.#{GeneratedNames.write_one}(element, writer, context, scope, child_filter)"
234
+ end
235
+ end
236
+ builder.line "end"
237
+ builder.line "writer.pop"
238
+ end
239
+
240
+ # Raw column bytes are pushed only after a strict parse accepts them; anything else
241
+ # (non-String, empty, malformed) falls back to the typed read.
242
+ def json_column_attribute(attribute, config, index, builder)
243
+ if config.json_column_emit == :html_safe
244
+ attribute(attribute, "record._read_attribute(#{GeneratedNames.string_literal(attribute.source)})", config, index, builder)
245
+ return
246
+ end
247
+ source_lit = GeneratedNames.string_literal(attribute.source)
248
+ key_lit = GeneratedNames.string_literal(attribute.name)
249
+ builder.line "unless filters.drops?(#{index})"
250
+ builder.indent do
251
+ builder.line %(raw = record.read_attribute_before_type_cast(#{source_lit}))
252
+ builder.line "if raw.is_a?(String) && !raw.empty? && (begin"
253
+ builder.indent do
254
+ builder.line "Oj.sc_parse(Panko::CodeGen::JSON_NOOP_PARSER, raw, Panko::CodeGen::JSON_STRICT_PARSE_OPTS)"
255
+ builder.line "true"
256
+ end
257
+ builder.line "rescue Oj::ParseError, EncodingError"
258
+ builder.indent do
259
+ builder.line "false"
260
+ end
261
+ builder.line "end)"
262
+ builder.indent do
263
+ builder.line "writer.push_json(raw, #{key_lit})"
264
+ end
265
+ builder.line "else"
266
+ builder.indent do
267
+ builder.line "writer.push_value(record._read_attribute(#{source_lit}), #{key_lit})"
268
+ end
269
+ builder.line "end"
270
+ end
271
+ builder.line "end"
272
+ end
273
+
274
+ def datetime_column_attribute(attribute, index, builder)
275
+ source_lit = GeneratedNames.string_literal(attribute.source)
276
+ builder.line "unless filters.drops?(#{index})"
277
+ builder.indent do
278
+ builder.line "value = Panko::CodeGen::DateTimeFormat.format_raw(record.read_attribute_before_type_cast(#{source_lit}))"
279
+ builder.line "writer.push_value(value || record._read_attribute(#{source_lit}), " \
280
+ "#{GeneratedNames.string_literal(attribute.name)})"
281
+ end
282
+ builder.line "end"
283
+ end
284
+ end
285
+ end
286
+ end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Panko::CodeGen
4
+ module Generators
5
+ module RecordAccess
6
+ # Both field bodies are inlined under one +is_a?(Hash)+ branch: this saves a call per record,
7
+ # and each arm owns its call sites, so a Hash and an object never share one inline cache.
8
+ module Generic
9
+ # Above this field count the two bodies go into separate helper methods, which halves each
10
+ # method's size for JITs that compile whole methods (ZJIT).
11
+ FUSED_DISPATCH_MAX_FIELDS = 64
12
+
13
+ def self.emit(descriptor, config, field_index, builder, sink, method_name: sink.entry_name)
14
+ return emit_split(descriptor, config, field_index, builder, sink, method_name: method_name) if split_dispatch?(descriptor)
15
+
16
+ builder.line "def #{method_name}(#{sink.entry_params})"
17
+ builder.indent do
18
+ emit_parent_class_ivar_writes(descriptor, builder)
19
+ builder.line "if record.is_a?(Hash)"
20
+ builder.indent do
21
+ FieldWalk.emit_fields(
22
+ descriptor, config, field_index, builder, sink,
23
+ read_expr: ->(source) { hash_read_expr(source, config) }
24
+ )
25
+ end
26
+ builder.line "else"
27
+ builder.indent do
28
+ FieldWalk.emit_fields(
29
+ descriptor, config, field_index, builder, sink,
30
+ read_expr: ->(source) { GeneratedNames.method_call("record", source) }
31
+ )
32
+ end
33
+ builder.line "end"
34
+ end
35
+ builder.line "end"
36
+ end
37
+
38
+ def self.emit_split(descriptor, config, field_index, builder, sink, method_name: sink.entry_name)
39
+ builder.line "def #{method_name}(#{sink.entry_params})"
40
+ builder.indent do
41
+ emit_parent_class_ivar_writes(descriptor, builder)
42
+ builder.line "if record.is_a?(Hash)"
43
+ builder.indent { builder.line "#{sink.split_hash_helper}(#{sink.entry_params})" }
44
+ builder.line "else"
45
+ builder.indent { builder.line "#{sink.split_object_helper}(#{sink.entry_params})" }
46
+ builder.line "end"
47
+ end
48
+ builder.line "end"
49
+ builder.blank
50
+ builder.line "def #{sink.split_hash_helper}(#{sink.entry_params})"
51
+ builder.indent do
52
+ FieldWalk.emit_fields(
53
+ descriptor, config, field_index, builder, sink,
54
+ read_expr: ->(source) { hash_read_expr(source, config) }
55
+ )
56
+ end
57
+ builder.line "end"
58
+ builder.blank
59
+ builder.line "def #{sink.split_object_helper}(#{sink.entry_params})"
60
+ builder.indent do
61
+ FieldWalk.emit_fields(
62
+ descriptor, config, field_index, builder, sink,
63
+ read_expr: ->(source) { GeneratedNames.method_call("record", source) }
64
+ )
65
+ end
66
+ builder.line "end"
67
+ end
68
+
69
+ def self.split_dispatch?(descriptor)
70
+ descriptor.attributes.size + descriptor.method_attributes.size + descriptor.associations.size >
71
+ FUSED_DISPATCH_MAX_FIELDS
72
+ end
73
+
74
+ # Only a Symbol-body Method Attribute reads +@object+ / +@context+ / +@scope+ on +self+;
75
+ # Callable bodies get them as arguments, so without one the writes are wasted work per record.
76
+ def self.emit_parent_class_ivar_writes(descriptor, builder)
77
+ return if descriptor.method_attributes.none? { |method_attribute| method_attribute.body.is_a?(Symbol) }
78
+ builder.line "@object = record"
79
+ builder.line "@context = context"
80
+ builder.line "@scope = scope"
81
+ end
82
+
83
+ def self.hash_read_expr(source_name, config)
84
+ case config.hash_record_key_type
85
+ when :symbol then "record[#{GeneratedNames.symbol_literal(source_name)}]"
86
+ else "record[#{GeneratedNames.string_literal(source_name)}]"
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Panko::CodeGen
4
+ module Generators
5
+ module RecordAccess
6
+ # Records are assumed to be instances of the Descriptor's Model, so there is no Hash branch.
7
+ module Specialized
8
+ def self.emit(descriptor, config, field_index, builder, sink)
9
+ ar_model = ar_model(descriptor)
10
+ builder.line "def #{sink.entry_name}(#{sink.entry_params})"
11
+ builder.indent do
12
+ emit_model_guard(descriptor, config, "#{sink.generic_entry_name}(#{sink.entry_params})", builder)
13
+ Generic.emit_parent_class_ivar_writes(descriptor, builder)
14
+ FieldWalk.emit_fields(
15
+ descriptor, config, field_index, builder, sink,
16
+ read_expr: ->(source) { GeneratedNames.method_call("record", source) },
17
+ attribute_emit: ->(attribute, index) { sink.specialized_attribute(attribute, ar_model, config, index, builder) }
18
+ )
19
+ end
20
+ builder.line "end"
21
+ emit_generic_twin(config, builder) do
22
+ Generic.emit(descriptor, config, field_index, builder, sink, method_name: sink.generic_entry_name)
23
+ end
24
+ end
25
+
26
+ # Under auto-specialization nothing promises every record has the Model's class, so a record of
27
+ # another class (Hash, STI sibling, mixed array) goes to the generic twin instead of wrong output.
28
+ def self.emit_model_guard(descriptor, config, fallback_call, builder)
29
+ return unless config.guarded_model
30
+ model_name = descriptor.model.name
31
+ if model_name.nil?
32
+ raise CompileError,
33
+ "#{descriptor.name}: guarded_model requires a named Model class; got anonymous #{descriptor.model.inspect}"
34
+ end
35
+ builder.line "return #{fallback_call} unless record.instance_of?(::#{model_name})"
36
+ end
37
+
38
+ def self.emit_generic_twin(config, builder)
39
+ return unless config.guarded_model
40
+ builder.blank
41
+ yield
42
+ end
43
+
44
+ # A method the Model does not declare as an attribute reads the loaded attribute first, so a
45
+ # SELECT alias named like a method (+thing_ids+ next to +has_many :things+) returns the selected value.
46
+ def self.attribute_read_expr(attribute, ar_model)
47
+ source = attribute.source
48
+ method_read = GeneratedNames.method_call("record", source)
49
+ return method_read if ar_model.nil?
50
+ source_lit = GeneratedNames.string_literal(source)
51
+ return "record._read_attribute(#{source_lit})" if ActiveRecord::AccessClassifier.classify(ar_model, source) == :column
52
+ return method_read if declared_attribute?(ar_model, source)
53
+ "(record._has_attribute?(#{source_lit}) ? record._read_attribute(#{source_lit}) : #{method_read})"
54
+ end
55
+
56
+ def self.declared_attribute?(ar_model, source)
57
+ ar_model.attribute_types.key?(source.to_s) || ar_model.attribute_aliases.key?(source.to_s)
58
+ end
59
+
60
+ # Called here too so the Generator works without the validators.
61
+ def self.ar_model(descriptor)
62
+ model = descriptor.model
63
+ return nil unless model.respond_to?(:columns_hash) && model.respond_to?(:attribute_methods_generated?)
64
+ model.define_attribute_methods
65
+ model
66
+ end
67
+
68
+ # Requires a +:column+ result because the column fast paths read past a user-overridden reader.
69
+ def self.json_column_attribute?(attribute, ar_model)
70
+ return false if ar_model.nil?
71
+ return false unless ActiveRecord::AccessClassifier.json_typed?(ar_model, attribute.source)
72
+ ActiveRecord::AccessClassifier.classify(ar_model, attribute.source) == :column
73
+ end
74
+
75
+ # Only under +:utc+ is the zoneless raw DB string really UTC, so the fast path's trailing "Z" is true.
76
+ # The +::+ matters: bare +ActiveRecord+ here resolves to +Panko::CodeGen::ActiveRecord+.
77
+ def self.datetime_column_attribute?(attribute, ar_model)
78
+ return false if ar_model.nil?
79
+ return false unless ::ActiveRecord.default_timezone == :utc
80
+ return false unless ActiveRecord::AccessClassifier.datetime_typed?(ar_model, attribute.source)
81
+ ActiveRecord::AccessClassifier.classify(ar_model, attribute.source) == :column
82
+ end
83
+
84
+ def self.plain_column_attribute?(attribute, ar_model)
85
+ return false if ar_model.nil?
86
+ return false unless ActiveRecord::AccessClassifier.plain_typed?(ar_model, attribute.source)
87
+ ActiveRecord::AccessClassifier.classify(ar_model, attribute.source) == :column
88
+ end
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Panko::CodeGen
4
+ module Generators
5
+ # A pooled instance that kept +@object+ / +@context+ / +@scope+ after
6
+ # checkin would keep the last record graph alive in fiber-local storage.
7
+ module Release
8
+ module_function
9
+
10
+ # Must match the gate in +RecordAccess::Generic.emit_parent_class_ivar_writes+.
11
+ def ivar_writes?(descriptor)
12
+ descriptor.method_attributes.any? { |method_attribute| method_attribute.body.is_a?(Symbol) }
13
+ end
14
+
15
+ # Must follow the same edges as {emit} so the answer matches the
16
+ # emitted code.
17
+ def subtree_releases?(descriptor, cyclic_ids, seen = {})
18
+ return false if seen[descriptor.__id__]
19
+ seen[descriptor.__id__] = true
20
+ return true if ivar_writes?(descriptor)
21
+ descriptor.associations.flat_map(&:descriptors).any? do |child|
22
+ next false if child.equal?(descriptor)
23
+ next false if cyclic_ids[descriptor.__id__] && cyclic_ids[child.__id__]
24
+ subtree_releases?(child, cyclic_ids, seen)
25
+ end
26
+ end
27
+
28
+ def child_ivars(assoc, position)
29
+ variants = assoc.variants.each_with_index.map do |variant, index|
30
+ [GeneratedNames.variant_serializer_ivar(position, index), variant]
31
+ end
32
+ [[GeneratedNames.serializer_ivar(position), assoc.descriptor], *variants]
33
+ end
34
+
35
+ # Every class defines +_release+, even an empty one: the serializers call it
36
+ # on every checkin without checking.
37
+ def emit(descriptor, builder, cyclic_ids)
38
+ builder.line "def _release"
39
+ builder.indent do
40
+ if ivar_writes?(descriptor)
41
+ builder.line "@object = nil"
42
+ builder.line "@context = nil"
43
+ builder.line "@scope = nil"
44
+ end
45
+ descriptor.associations.each_with_index do |assoc, position|
46
+ child_ivars(assoc, position).each do |ivar, child|
47
+ next if child.equal?(descriptor)
48
+ # Ends the chain without per-call visited state; such serializers keep their last record until the next call.
49
+ next if cyclic_ids[descriptor.__id__] && cyclic_ids[child.__id__]
50
+ next unless subtree_releases?(child, cyclic_ids)
51
+ builder.line "#{ivar}._release"
52
+ end
53
+ end
54
+ builder.line "nil"
55
+ end
56
+ builder.line "end"
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Panko::CodeGen
4
+ module Generators
5
+ class Sink
6
+ # The child's +FIELD_INDEX+ is read through its class name when the method runs, so
7
+ # self-recursive Descriptors resolve it.
8
+ def child_filter_expr(association)
9
+ "filters.child(#{GeneratedNames.symbol_literal(GeneratedNames.filter_key(association))}, " \
10
+ "#{GeneratedNames.class_name(association.descriptor, suffix)}::#{GeneratedNames.field_index_const})"
11
+ end
12
+
13
+ # +case+/+when+, not an +if+/+elsif+ chain of +instance_of?+: under YJIT the chain gets
14
+ # slower once the call site has warmed on one class. HashSink uses the +case+ as an expression.
15
+ def child_write(association, position, record_expr, builder, &call_for)
16
+ base_call = call_for.call(GeneratedNames.serializer_ivar(position))
17
+ if association.variants.empty?
18
+ builder.line base_call
19
+ return
20
+ end
21
+ builder.line "case #{record_expr}"
22
+ subclass_first(association.variants).each do |variant, index|
23
+ model = "::#{variant.model.name}"
24
+ builder.line "when #{model}"
25
+ builder.indent do
26
+ builder.line "if #{record_expr}.instance_of?(#{model})"
27
+ builder.indent { builder.line call_for.call(GeneratedNames.variant_serializer_ivar(position, index)) }
28
+ builder.line "else"
29
+ builder.indent { builder.line base_call }
30
+ builder.line "end"
31
+ end
32
+ end
33
+ builder.line "else"
34
+ builder.indent { builder.line base_call }
35
+ builder.line "end"
36
+ end
37
+
38
+ # Each subclass before its ancestors, so a parent's +when+ arm does not take a declared
39
+ # subclass.
40
+ def subclass_first(variants)
41
+ variants.each_with_index.sort_by { |variant, index| [-variant.model.ancestors.size, index] }
42
+ end
43
+
44
+ # The guard wraps the Source read too, so a falsy +if:+ skips the read.
45
+ def with_if_guard(association, position, builder)
46
+ if association.if
47
+ builder.line "if #{if_guard_call_expression(GeneratedNames.if_guard_ivar(position), association.if.arity)}"
48
+ builder.indent { yield }
49
+ builder.line "end"
50
+ else
51
+ yield
52
+ end
53
+ end
54
+
55
+ # The +callable_arity+ rule limits arity to +0..3+, so +else+ is arity 3.
56
+ def if_guard_call_expression(ivar, arity)
57
+ case arity
58
+ when 0 then "#{ivar}.call"
59
+ when 1 then "#{ivar}.call(record)"
60
+ when 2 then "#{ivar}.call(record, context)"
61
+ else "#{ivar}.call(record, context, scope)"
62
+ end
63
+ end
64
+
65
+ # Symbol bodies need the explicit +self.+: a bare name such as +record+ or +value+ would
66
+ # resolve to a local of the generated method.
67
+ def method_attribute_call_expression(method_attribute, position)
68
+ body = method_attribute.body
69
+ return GeneratedNames.method_call("self", body) if body.is_a?(Symbol)
70
+ ivar = GeneratedNames.callable_ivar(position)
71
+ case body.arity
72
+ when 0 then "#{ivar}.call"
73
+ when 1 then "#{ivar}.call(record)"
74
+ when 2 then "#{ivar}.call(record, context)"
75
+ else "#{ivar}.call(record, context, scope)"
76
+ end
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Panko::CodeGen
4
+ # Fiber-local stack of Generated Class instances. An instance cannot be shared: writing a record
5
+ # can set +@object+/+@context+/+@scope+, so a nested serialize of the same class needs its own.
6
+ #
7
+ # After a code reload or SerializerCache.reset!, each fiber keeps its old stack (and the old
8
+ # class) until it ends. Accepted: reloads are a development feature and reset! is for tests.
9
+ class InstancePool
10
+ def initialize(key, compiled, descriptor)
11
+ # The pool's own object_id keeps a pool rebuilt after SerializerCache.reset! off the old
12
+ # pool's stacks, which hold instances of the old compiled class.
13
+ @key = :"#{key}_#{object_id}"
14
+ @compiled = compiled
15
+ @descriptor = descriptor
16
+ end
17
+
18
+ # Returns the stack itself so a checkout and checkin cost one +Thread.current+ lookup.
19
+ def stack
20
+ Thread.current[@key] ||= []
21
+ end
22
+
23
+ def build
24
+ @compiled.new(descriptor: @descriptor)
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../code_gen"
4
+ require_relative "serializer_cache"
5
+ require_relative "filter_adapter"
6
+
7
+ module Panko
8
+ module CodeGen
9
+ module Runtime
10
+ module_function
11
+
12
+ def runtime_filters(serializer_class, context, scope, only, except)
13
+ if serializer_class.respond_to?(:filters_for)
14
+ overrides = serializer_class.filters_for(context, scope) || {}
15
+ only = overrides.fetch(:only, only)
16
+ except = overrides.fetch(:except, except)
17
+ end
18
+ return nil if blank?(only) && blank?(except)
19
+ FilterAdapter.to_engine_filters(blank?(only) ? nil : only, blank?(except) ? nil : except)
20
+ end
21
+
22
+ def blank?(filter)
23
+ filter.nil? || (filter.respond_to?(:empty?) && filter.empty?)
24
+ end
25
+ end
26
+ end
27
+ end