1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
| #### libremiliacr
#### Copyright(C) 2020-2024 Remilia Scarlet <remilia@posteo.jp>
####
#### This program is free software: you can redistribute it and/or modify it
#### under the terms of the GNU General Public License as published the Free
#### Software Foundation, either version 3 of the License, or (at your option)
#### any later version.
####
#### This program is distributed in the hope that it will be useful, but WITHOUT
#### ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#### FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public License for
#### more details.
####
#### You should have received a copy of the GNU General Public License along
#### with this program.If not, see<http:####www.gnu.org/licenses/.>
require "./common"
module RemiLib::RSConf
# Annotates a field in a class or struct to provide additional options when
# (de)serializing RSConf data.
#
# Possible options are:
#
# * **ignore**: if `true` skip this field in serialization and deserialization
# (by default false)
# * **neverSerialize**: If truthy, skip this field in serialization (default:
# `false`). The value can be any Crystal expression and is evaluated at
# runtime.
# * **neverDeserialize**: if `true` skip this field in deserialization (by
# default false)
# * **key**: the value of the key in the RSConf object (by default the name of
# the instance variable)
# * **root**: assume the value is inside an RSConf object with a given key
# (see `Object.fromRSConf(stringOrIO, root)`)
# * **converter**: specify an alternate type for parsing and generation. The
# converter must define `fromRsconf(RemiLib::RSConf::RSValue)` and
# `toRsconf(value, RemiLib::RSConf::RSValue)`. Examples of converters are a
# `Time::Format` instance and `Time::EpochConverter` for `Time`.
# * **presence**: if `true`, a `@{{key}}Present` instance variable and a
# `#getter?` with the same name will be generated when the key was present
# (even if it has a `null` value), `false` by default
# * **emitNull**: if `true`, emits a `null` value for nilable property (by
# default nulls are not emitted)
# * **blanksBefore**: the number of blank lines to print before this field is
# written. This occurs after any `Serializable#beforeToRsconf` method is
# called, and before any comment is written. Default is 0.
# * **blanksAfter**: the number of blank lines to print after this field is
# written. This occurs before any `Serializable#afterToRsconf` method is
# called, and (if using `RemiLib::RSConf::Serializable::Unmapped`), before
# any unmapped fields are written. Default is 0.
# * **commentBefore**: A comment string to write before the field is written.
# This occurs after any `Serializable#beforeToRsconf` method is called.
# This cannot be used together with the **commentFnBefore** property.
# * **commentFnBefore**: A function that must return a string. This will be
# called before the field is written, and its return value will be written
# as a comment. This occurs after any `Serializable#beforeToRsconf` method
# is called. This cannot be used together with the **commentBefore**
# property.
# * **commentIsBlock**: When `true`, then the **commentBefore** or
# **commentFnBefore** field is written using
# `RemiLib::RSConf::Builder#writeBlockComment`. Default is `false`.
annotation Field
end
# The `RemiLib::RSConf::Serializable` module automatically generates methods
# for RSConf serialization when included.
#
# ### Example
#
# ```
# require "libremiliacr"
#
# alias RSConf = RemiLib::RSConf
#
# class Location
# include RSConf::Serializable
#
# @[RSConf::Field(key: "lat")]
# property latitude : Float64
#
# @[RSConf::Field(key: "long")]
# property longitude : Float64
# end
#
# class House
# include RSConf::Serializable
# property address : String
# property location : Location?
# end
#
# rsStr = %|
# address = "Crystal Road 1234"
# location = {
# lat: 12.3
# long: 34.5
# }
# |
#
# parsed = RSConf::Parser.parse(rsStr)
# house = House.fromRsconf(parsed)
# house.address # => "Crystal Road 1234"
# house.location # => #<Location:0x10cd93d80 @latitude=12.3, @longitude=34.5>
# ```
#
# ### Usage
#
# Including `RemiLib::RSConf::Serializable` will create `#toRsconf` and
# `self.fromRsconf` methods on the current class, and a constructor which
# takes a `RemiLib::RSConf::RSValue`. By default, these methods serialize into
# an RSConf object containing the value of every instance variable, the keys
# being the instance variable name. Most primitives and collections supported
# as instance variable values (string, integer, array, hash, etc.), along with
# objects which define toRsconf and a constructor taking a
# `oRemiLib::RSConf::RSValue`. Union types are also supported, including
# unions with `nil`. If multiple types in a union parse correctly, it is
# undefined which one will be chosen.
#
# To change how individual instance variables are parsed and serialized, the
# annotation `RemiLib::RSConf::Field` can be placed on the instance
# variable. Annotating property, getter and setter macros is also allowed.
#
# ```
# require "libremiliacr"
# alias RSConf = RemiLib::RSConf
#
# class A
# include RSConf::Serializable
#
# @[RSConf::Field(key: "my_key", emitNull: true)]
# getter a : Int32?
# end
# ```
#
# `RemiLib::RSConf::Field` properties:
#
# * **ignore**: if `true` skip this field in serialization and deserialization
# (by default false)
# * **neverSerialize**: If truthy, skip this field in serialization (default:
# `false`). The value can be any Crystal expression and is evaluated at
# runtime.
# * **neverDeserialize**: if `true` skip this field in deserialization (by
# default false)
# * **key**: the value of the key in the RSConf object (by default the name of
# the instance variable)
# * **root**: assume the value is inside an RSConf object with a given key
# (see `Object.fromRSConf(stringOrIO, root)`)
# * **converter**: specify an alternate type for parsing and generation. The
# converter must define `fromRsconf(RemiLib::RSConf::RSValue)` and
# `toRsconf(value, RemiLib::RSConf::RSValue)`. Examples of converters are a
# `Time::Format` instance and `Time::EpochConverter` for `Time`.
# * **presence**: if `true`, a `@{{key}}Present` instance variable and a
# `#getter?` with the same name will be generated when the key was present
# (even if it has a `null` value), `false` by default
# * **emitNull**: if `true`, emits a `null` value for nilable property (by
# default nulls are not emitted)
# * **blanksBefore**: the number of blank lines to print before this field is
# written. This occurs after any `#beforeToRsconf` method is
# called, and before any comment is written. Default is 0.
# * **blanksAfter**: the number of blank lines to print after this field is
# written. This occurs before any `#afterToRsconf` method is called, and
# (if using `RemiLib::RSConf::Serializable::Unmapped`), before any unmapped
# fields are written. Default is 0.
# * **commentBefore**: A comment string to write before the field is written.
# This occurs after any `#beforeToRsconf` method is called. This cannot be
# used together with the **commentFnBefore** property.
# * **commentFnBefore**: A function that must return a string. This will be
# called before the field is written, and its return value will be written
# as a comment. This occurs after any `#beforeToRsconf` method is called.
# This cannot be used together with the **commentBefore** property.
# * **commentIsBlock**: When `true`, then the **commentBefore** or
# **commentFnBefore** field is written using
# `RemiLib::RSConf::Builder#writeBlockComment`. Default is `false`.
#
# Deserialization also respects default values of variables:
# ```
# require "libremiliacr"
# alias RSConf = RemiLib::RSConf
#
# struct A
# include RSConf::Serializable
# @a : Int32
# @b : Float64 = 1.0
# end
#
# data = RSConf::Parser.parse(%|a = 1|)
# A.fromRsconf(data) # => A(@a=1, @b=1.0)
# ```
#
# ### Extensions: `RemiLib::RSConf::Serializable::Strict` and
# ### `RemiLib::RSConf::Serializable::Unmapped`.
#
# If the `RemiLib::RSConf::Serializable::Strict` module is included, unknown
# properties in the RSConf document will raise a parse exception. By default
# the unknown properties are silently ignored. If the
# `RemiLib::RSConf::Serializable::Unmapped` module is included, unknown
# properties in the RSConf document will be stored in a `Hash(String,
# RemiLib::RSConf::RSValue)`. On serialization, any keys inside
# `rsconfUnmapped` will be serialized and appended to the current RSConf
# object.
#
# ```
# require "libremiliacr"
# alias RSConf = RemiLib::RSConf
#
# struct A
# include RSConf::Serializable
# include RSConf::Serializable::Unmapped
# @a : Int32
# end
#
# data = RSConf::Parser.parse($|a = 1, b = 2|)
# a = A.fromRsconf(data) # => A(@rsconfUnmapped={"b" => 2}, @a=1)
# a.rsconfUnmapped["b"].raw.class # => Int64
# ```
#
#
# ### Class annotation `RemiLib::RSConf::Serializable::Options`
#
# Supported properties:
#
# * **emitNulls**: if `true`, emits a `null` value for all nilable properties
# (by default nulls are not emitted)
#
#
# ```
# require "libremiliacr"
# alias RSConf = RemiLib::RSConf
#
# @[RSConf::Serializable::Options(emitNulls: true)]
# class A
# include RSConf::Serializable
# @a : Int32?
# end
# ```
#
# ### `after_initialize` method
#
# `#after_initialize` is a method that runs after an instance is deserialized
# from RSConf. It can be used as a hook to post-process the initialized
# object.
#
# Example:
# ```
# require "libremiliacr"
# alias RSConf = RemiLib::RSConf
#
# class Person
# include RSConf::Serializable
# getter name : String
#
# def after_initialize
# @name = @name.upcase
# end
# end
#
# data = RSConf::Parser.parse("name: jane")
# person = Person.fromRsconf(data)
# person.name # => "JANE"
# ```
module Serializable
# This annotation can be attached to classes and structs to provide RSConf
# (de)serialization options.
#
# Possible options are:
# * **emitNulls**: if `true`, emits a `null` value for all nilable
# properties (by default nulls are not emitted).
annotation Options
end
macro included
# Creates a new instance by deserializing data from a
# `RemiLib::RSConf::RSValue`.
def self.new(toplevel : ::RemiLib::RSConf::RSValue)
newFromRSConfTopLevel(toplevel)
end
private def self.newFromRSConfTopLevel(toplevel : ::RemiLib::RSConf::RSValue)
instance = allocate
instance.initialize(__fromRSConfTopLevel: toplevel)
::GC.add_finalizer(instance) if instance.responds_to?(:finalize)
instance
end
macro inherited
def self.new(toplevel : ::RemiLib::RSConf::RSValue)
newFromRSConfTopLevel(toplevel)
end
end
end
# Called internally to perform the actual deserialization from an
# `RemiLib::RSConf::RSValue`.
def initialize(*, __fromRSConfTopLevel toplevel : ::RemiLib::RSConf::RSValue)
{% begin %}
unless toplevel.is_a?(::RemiLib::RSConf::RSObject)
raise ::RemiLib::RSConf::RSConfSerializationError.new("Toplevel is not an object.")
end
{% properties = {} of Nil => Nil %}
{% for ivar in @type.instance_vars %}
{% ann = ivar.annotation(::RemiLib::RSConf::Field) %}
{% unless ann && (ann[:ignore] || ann[:neverDeserialize]) %}
{%
properties[ivar.id] = {
key: ((ann && ann[:key]) || ivar).id.stringify, # The name of the field
hasDefault: ivar.has_default_value?, # Whether or not this field has a default value
default: ivar.default_value, # The default value for this field, if any
nilable: ivar.type.nilable?, # Whether or not this field is nillable
type: ivar.type, # The type of this field
root: ann && ann[:root], # This field's value is in a key directly underneath with this name
converter: ann && ann[:converter], # A conversion type
presence: ann && ann[:presence], # Whether or not a "presence" field is also generated
}
%}
{% end %}
{% end %}
# `%var`'s type must be exact to avoid type inference issues with
# recursively defined serializable types
{% for name, value in properties %}
%var{name} = uninitialized ::Union({{value[:type]}})
%found{name} = false
{% end %}
# Loop through all of toplevel's pairs, checking to see if we can
# deserialize the pair into a field.
toplevel.each do |%key, %val|
# Match this object's key to one of the field names.
case %key
{% for name, value in properties %}
when {{value[:key]}}
{% if value[:hasDefault] || value[:nilable] %}
# Take care of null values right away
if %val.is_a?(::RemiLib::RSConf::RSScalar) && %val.nil?
{% if value[:nilable] %}
%var{name} = nil
%found{name} = true
{% end %}
next
end
{% end %}
{% if value[:root] %}
# This key expects its value in a subnode.
if %val.is_a?(::RemiLib::RSConf::RSObject)
if %val.has_key?({{value[:root]}})
begin
{% if value[:converter] %}
%subval = {{value[:converter]}}.fromRsconf(%val[{{value[:root]}}])
{% else %}
%subval = {{value[:type]}}.fromRsconf(%val[{{value[:root]}}])
{% end %}
rescue err : ::RemiLib::RSConf::RSConfError
raise ::RemiLib::RSConf::RSConfError.new("Bad value for key '#{%key}': #{err}", err)
end
{% if value[:hasDefault] %}
else
%subval = {{value[:default]}}
{% else %}
else
raise RSConfSerializationError.new("Missing root node for key '#{%key}'")
{%end%}
end
{% if value[:hasDefault] %}
elsif %val.is_a?(RSScalar) && %val.nil?
%subval = {{value[:default]}}
{% else %}
else
raise RSConfSerializationError.new("Root node for key '#{%key}' is not an object")
{%end%}
end
%var{name} = %subval
next
{% else %}
# This key expects is value directly (i.e. this doesn't use the
# 'root' field option)
begin
{% if value[:converter] %}
%var{name} = {{value[:converter]}}.fromRsconf(%val)
{% else %}
%var{name} = {{value[:type]}}.fromRsconf(%val)
{% end %}
rescue err : ::RemiLib::RSConf::RSConfError
raise ::RemiLib::RSConf::RSConfError.new("Bad value for key '#{%key}': #{err}", err)
end
{% end %}
%found{name} = true
{% end %}
else
onUnknownRSConfAttribute(%key, %val)
end
end
{% for name, value in properties %}
if %found{name}
@{{name}} = %var{name}
else
{% unless value[:hasDefault] || value[:nilable] %}
raise ::RemiLib::RSConf::RSConfSerializationError.new("Missing RSConf attribute: {{value[:key].id}}")
{% end %}
end
{% if value[:presence] %}
@{{name}}Present = %found{name}
{% end %}
{% end %}
{% end %}
after_initialize
end
# Called after deserialization is completed.
def after_initialize
end
protected def onUnknownRSConfAttribute(key, value)
end
# Called immediately before this object is serialized to RSConf.
def beforeToRsconf(builder : ::RemiLib::RSConf::Builder) : Nil
end
# Called immediately after this object is serialized to RSConf.
def afterToRsconf(builder : ::RemiLib::RSConf::Builder) : Nil
end
# Called after the key/value pairs for this object are serialized to RSConf,
# but before the object is closed out.
protected def toRsconfBeforeObjectFinished(builder : ::RemiLib::RSConf::Builder) : Nil
end
# Serializes this instance to RSConf data.
def toRsconf(builder : ::RemiLib::RSConf::Builder)
{% begin %}
{% options = @type.annotation(::RemiLib::RSConf::Serializable::Options) %}
{% emitNulls = options && options[:emitNulls] %}
{% properties = {} of Nil => Nil %}
{% for ivar in @type.instance_vars %}
{% ann = ivar.annotation(::RemiLib::RSConf::Field) %}
{% unless ann && (ann[:ignore] || ann[:neverSerialize] == true) %}
{%
properties[ivar.id] = {
key: ((ann && ann[:key]) || ivar).id.stringify,
root: ann && ann[:root],
converter: ann && ann[:converter],
emitNull: (ann && (ann[:emitNull] != nil) ? ann[:emitNull] : emitNulls),
neverSerialize: ann && ann[:ignoreSerialize],
blanksBefore: ann && (ann[:blanksBefore] || 0),
blanksAfter: ann && (ann[:blanksAfter] || 0),
commentBefore: ann && ann[:commentBefore],
commentFnBefore: ann && ann[:commentFnBefore],
commentIsBlock: ann && ann[:commentIsBlock],
}
%}
{% if properties[ivar.id][:commentBefore] && properties[ivar.id][:commentFnBefore] %}
{% raise "Cannot use both commentBefore and commentFnBefore in a RemiLib::RSConf::Field" %}
{% end %}
{% end %}
{% end %}
beforeToRsconf(builder)
builder.writeObject do
{% for name, value in properties %}
_{{name}} = @{{name}}
{% if value[:neverSerialize] %}
unless {{ value[:neverSerialize] }}
{% end %}
{% unless value[:emitNull] %}
unless _{{name}}.nil?
{% end %}
{% if value[:blanksBefore] %}
{% for i in 1..value[:blanksBefore] %}
builder.writeBlankLine
{% end %}
{% end %}
{% if value[:commentBefore] %}
{% if value[:commentIsBlock] %}
builder.writeBlockComment({{value[:commentBefore]}})
{% else %}
builder.writeComment({{value[:commentBefore]}})
{% end %}
{% end %}
{% if value[:commentFnBefore] %}
{% if value[:commentIsBlock] %}
builder.writeBlockComment({{value[:commentFnBefore]}})
{% else %}
builder.writeComment({{value[:commentFnBefore]}})
{% end %}
{% end %}
builder.writePair({{value[:key]}}) do
{% if value[:root] %}
{% if value[:emitNull] %}
if _{{name}}.nil?
builder.writeNil
else
{% end %}
builder.writeObject do
builder.writePair({{value[:root]}}) do
{% end %}
{% if value[:converter] %}
if _{{name}}
{{ value[:converter] }}.toRsconf(_{{name}}, builder)
else
builder.writeNil
end
{% else %}
_{{name}}.toRsconf(builder)
{% end %}
{% if value[:root] %}
{% if value[:emitNull] %}
end
{% end %}
end
end
{% end %}
end
{% unless value[:emitNull] %}
end
{% end %}
{% if value[:neverSerialize] %}
end
{% end %}
{% if value[:blanksAfter] %}
{% for i in 1..value[:blanksAfter] %}
builder.writeBlankLine
{% end %}
{% end %}
{% end %}
toRsconfBeforeObjectFinished(builder)
end
afterToRsconf(builder)
{% end %}
end
# If the `RemiLib::RSConf::Serializable::Strict` module is included, unknown
# properties in the RSConf document encountered during deserialization will
# raise a parse exception. Without this, unknown properties are silently
# ignored during deserialization.
module Strict
protected def onUnknownRSConfAttribute(key, value)
raise ::RemiLib::RSConf::RSConfSerializationError.new("Unknown RSConf attribute: #{key}")
end
end
# If the `RemiLib::RSConf::Serializable::Unmapped` module is included,
# unknown properties in the RSConf document encountered during
# deserialization will be stored in a `Hash(String, RemiLib::RSConf::RSValue)`.
# On serialization, any keys inside `#rsconfUnmapped` will be serialized and
# appended to the current RSConf object.
module Unmapped
@[RemiLib::RSConf::Field(ignore: true)]
property rsconfUnmapped : Hash(String, ::RemiLib::RSConf::RSValue) =
Hash(String, ::RemiLib::RSConf::RSValue).new
protected def onUnknownRSConfAttribute(key, value)
@rsconfUnmapped[key] = value
end
protected def toRsconfBeforeObjectFinished(builder : ::RemiLib::RSConf::Builder) : Nil
@rsconfUnmapped.each do |key, val|
builder.writePair(key, val)
end
end
end
end
end
|