-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathvalue.cr
617 lines (528 loc) · 14.7 KB
/
value.cr
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
require "../object"
require "./undefined"
require "./safe_string"
require "./callable"
class Crinja
# :nodoc:
alias Number = Float64 | Int64 | Int32
# Raw type wrapped by `Value`.
alias Raw = Number | String | Bool | Time | Crinja::Object | Undefined | Callable | Callable::Proc | SafeString | Dictionary | Array(Value) | Iterator(Value) | Nil
alias Dictionary = Hash(Value, Value)
# FIXME
# class Dictionary < Hash(Value, Value)
# def []=(key, value)
# self[Value.new(key)] = Value.new value
# end
# def [](key)
# self[Value.new(key)]
# end
# end
# Casts an object with hash-like interface to `Dictionary`.
def self.dictionary(object) : Dictionary
Dictionary.new.tap do |dict|
object.each do |key, value|
dict[Value.new(key)] = Value.new value
end
end
end
alias Variables = Hash(String, Value)
# FIXME
# class Variables < Hash(String, Value)
# def []=(key : String, value)
# self[key] = Value.new value
# end
# end
# Casts an object with hash-like interface to `Variables`, which can be
# used for name lookup.
def self.variables(object) : Variables
Variables.new.tap do |variables|
object.each do |k, v|
variables[k.to_s] = Value.new v
end
end
end
def self.value(value) : Value
# This methods cast datastructures with Crystal types like `Array(String)`
# to Crinja::Value.
case value
when Hash
Value.new Crinja.dictionary(value)
when NamedTuple
dict = Dictionary.new
value.each do |k, v|
dict[Value.new k.to_s] = value(v)
end
Value.new dict
when ::Tuple
Value.new Crinja::Tuple.from(value)
when Array
array = value.map do |item|
value(item).as(Value)
end
Value.new array
when Range
# TODO: Implement range trough pyobject `getattr`
Value.new value.to_a
when Iterator(Value)
Value.new value
when Iterator
Value.new Value::Iterator.new(value)
when Char
Value.new value.to_s
when Value
value
when Raw
Value.new value
when .responds_to? :raw
# match JSON::Any | YAML::Any without including json and yaml
value value.raw
else
raise "type error: can't wrap #{value.class} in Crinja::Value"
end
end
end
# `Value` represents an object inside the Crinja runtime.
#
# It wraps a Crystal value in `#raw` and defines methods to access
# properties of the wrapped value while being agnostic about the
# actual type of the wrapped raw value.
struct Crinja::Value
include Enumerable(self)
include Iterable(self)
include Comparable(self)
getter raw : Raw
def self.new(value : self) : self
value
end
def self.new(value) : self
Crinja.value(value)
end
def initialize(@raw : Raw)
end
# Assumes the underlying value responds to `size` and returns
# its size.
def size : Int
if (object = @raw).responds_to?(:size)
object.size
else
raise TypeError.new(self, "#{object.class} does not respond to #size")
end
end
# Assumes the underlying value is an `Indexable` or `String` returns the element
# at the given index.
# Raises if the underlying value is not an `Indexable` or `String`.
def [](index : Int) : Value
case object = @raw
when Indexable
Value.new object[index]
when String
Value.new object[index].to_s
else
raise TypeError.new(self, "expected Array for #[](index : Int), not #{object.class}")
end
end
# Assumes the underlying value is an `Indexable` or `String` and returns the element
# at the given index, or `nil` if out of bounds.
# Raises if the underlying value is not an `Indexable` or `String`.
def []?(index : Int) : Value?
case object = @raw
when Indexable
value = object[index]?
value ? Value.new(value) : nil
when String, SafeString
value = object[index]?
value ? Value.new(value.to_s) : nil
else
raise TypeError.new(self, "expected Indexable for #[]?(index : Int), not #{object.class}")
end
end
# Assumes the underlying value has an hash-like accessor and returns the element
# with the given key.
# Raises if the underlying value is not hash-like.
def [](key : String) : Value
Value.new Resolver.resolve_attribute(key, @raw)
end
# Assumes the underlying value has an hash-like accessor returns the element
# with the given key, or `nil` if the key is not present.
# Raises if the underlying value is not hash-like.
def []?(key : String) : Value?
Value.new Resolver.resolve_attribute(key, @raw)
end
# Assumes the underlying value is an `Iterable`, `Hash` or `String` and returns the first
# item in the list or the first character of the string.
def first
case object = @raw
when Dictionary
Value.new(Crinja::Tuple.new(object.first_key, object.first_value))
when Iterable
Value.new object.first
when String
Value.new object[0, 1]
else
raise TypeError.new(self, "expected Iterable, Hash or String for #first, not #{object.class}")
end
end
# Assumes the underlying value is a `String` or responds to `last` and returns the last
# item in the list or the last character of the string.
def last
object = @raw
if object.responds_to?(:last)
Value.new object.last
elsif object.is_a?(String)
Value.new object[-1, 1]
else
raise TypeError.new(self, "expected Enumerable or String for #last, not #{object.class}")
end
end
# Returns an iterator for the underlying value if it is an `Iterable`, `String` or `Undefined`
# which iterates through the items as `Value`.
def raw_each : ::Iterator
case object = @raw
when Hash
HashTupleIterator.new(object.each)
when Iterable(Value)
RawIterator.new(object.each)
when Iterable
object.each
when ::Iterator(Value)
RawIterator.new(object)
when ::Iterator
object
when String
object.each_char.map { |char| char.to_s }
when StrictUndefined
raise TypeError.new(self, "can't iterate over undefined")
when Undefined
([] of Nil).each
else
raise TypeError.new(self, "#{object.class} is not iterable")
end
end
# Returns an iterator for the underlying value if it is an `Iterable`, `String` or `Undefined`
# which iterates through the items as `Value`.
def each
Iterator.new(raw_each)
end
# Assumes the underlying value is an `Iterable` and yields each
# of the elements or key/values, always as `Value`.
def raw_each
case object = @raw
when Hash
object.each { |key, value| yield Crinja::Tuple.from({key, value}) }
when Iterable(Value), ::Iterator(Value)
object.each { |value| yield value.as(Value).raw }
when Iterable, ::Iterator
object.each { |value| yield value }
when String
object.each_char { |char| yield char.to_s }
when StrictUndefined
raise TypeError.new(self, "can't iterate over undefined")
when Undefined
else
raise TypeError.new(self, "#{object.class} is not iterable")
end
end
# Assumes the underlying value is an `Iterable` and yields each
# of the elements or key/values, always as `Value`.
def each
raw_each do |raw|
yield Value.new raw
end
end
# :nodoc:
class RawIterator
include ::Iterator(Raw)
include IteratorWrapper
def initialize(@iterator : ::Iterator(Value))
end
def next
value = wrapped_next
case value
when Value
value.raw
when stop
stop
else
# TODO: should never be reached, maybe raise?
Crinja::UNDEFINED
end
end
end
class Iterator(T)
include ::Iterator(Value)
include IteratorWrapper
@iterator : T
def initialize(@iterator : T)
end
def ==(other : Iterator)
@iterator == other.@iterator
end
def next : Value | Iterator::Stop
value = wrapped_next
case value
when Iterator::Stop
stop
else
Value.new(value)
end
end
end
# Checks that the underlying value is `Nil`, and returns `nil`. Raises otherwise.
def as_nil : Nil
raw_as(Nil)
end
# Checks that the underlying value is `String | SafeString`, and returns its value. Raises otherwise.
def as_s_or_safe
raw_as(String | SafeString)
end
# Checks that the underlying value is `String | SafeString | Nil`, and returns the value as `String`. Raises otherwise.
#
# If the value is `SafeString` it is unwrapped as `String`.
def as_s?
@raw.as(String | SafeString | Nil).try(&.to_s)
end
# Checks that the underlying value is `String`, and returns the value as `String`. Raises otherwise.
#
# If the value is `SafeString` it is unwrapped as `String`.
def as_s
@raw.as(String | SafeString).to_s
end
# :ditto:
@[Deprecated("Use `#as_s` instead")]
def as_s!
as_s
end
# Checks that the underlying value is `Array`, and returns its value. Raises otherwise.
def as_a : Array(Value)
raw_as(Array)
end
# Checks that the underlying value is `Hash`, and returns its value. Raises otherwise.
def as_h : Dictionary
raw_as(Hash)
end
# Checks that the underlying value is a `Crinja::Number`, and returns its value. Raises otherwise.
def as_number : Number
raw_as(Number)
end
# Checks that the underlaying value is a `Time` object and retuns its value. Raises otherwise.
def as_time
raw_as(Time)
end
# Checks that the underlaying value is a `Iterable` and retuns its value. Raises otherwise.
def as_iterable
raw_as(Iterable)
end
# Checks that the underlaying value is a `Indexable` and retuns its value. Raises otherwise.
def as_indexable
raw.as(Indexable)
end
# Checks that the underlaying value is a `Callable | Callable::Proc` and retuns its value. Raises otherwise.
def as_callable
raw_as(Callable | Callable::Proc)
end
def as_undefined
raw_as(Undefined)
end
def raw_as(type : T.class) forall T
raise_undefined! unless type == Undefined
begin
@raw.as(T)
rescue exc : TypeCastError
raise Crinja::Error.new("Unexpected type in Crinja value", cause: exc)
end
end
private def raise_undefined!
if (undefined = @raw).is_a?(Undefined)
raise UndefinedError.new(undefined)
end
end
def to_a
if (raw = @raw).is_a?(Array)
return raw
end
array = [] of Value
each do |item|
array << item
end
array
end
# :nodoc:
def inspect(io)
io << "Crinja::Value<"
@raw.inspect(io)
io << ">"
end
def pretty_print(pp : Crinja::PrettyPrint)
@raw.pretty_print(pp)
end
# :nodoc:
def to_s(io)
@raw.to_s(io)
end
# :nodoc:
def to_s
if (raw = @raw).is_a?(String)
raw
else
super
end
end
def to_json(builder : JSON::Builder)
Crinja::JsonBuilder.to_json(builder, self)
end
# Transform the value into a string representation.
def to_string
raise_undefined!
Finalizer.stringify(@raw)
end
# Returns `true` if both `self` and *other*'s raw object are equal.
def ==(other : Value)
@raw == other.raw
end
# Returns `true` if the raw object is equal to *other*.
def ==(other)
@raw == other
end
# Compares this value to *other*.
#
# TODO: Enable proper comparison.
def <=>(other : Value)
otherraw = other.raw
if @raw.is_a?(String | SafeString) || otherraw.is_a?(String | SafeString)
as_s <=> other.as_s
elsif number? && other.number?
as_number <=> other.as_number
# elsif thisraw.is_a?(Array) && otherraw.is_a?(Array)
# thisraw <=> otherraw
else
raise TypeError.new("cannot compare #{@raw.class} with #{otherraw.class}")
end
end
def <=>(other : Value)
compare raw, other.raw
end
private def compare(a, b)
if a.is_a?(Array)
if b.is_a?(Array)
compare_array(a, b)
else
raise TypeError.new "Cannot compare Array with #{b.class}"
end
elsif a.is_a?(Bool) || b.is_a?(Bool)
raise TypeError.new "Cannot compare Bool value"
elsif a.is_a?(Number) && b.is_a?(Number)
a <=> b
elsif a.is_a?(String | SafeString) || a.is_a?(String | SafeString)
a.to_s <=> b.to_s
else
raise TypeError.new("cannot compare #{a.class} with #{b.class}")
end
end
private def compare_array(a : Array, b : Array)
# reimplement Array#<=>
min_size = Math.min(a.size, b.size)
0.upto(min_size - 1) do |i|
n = a[i] <=> b[i]
return n if n != 0
end
a.size <=> b.size
end
# :nodoc:
def hash
raw.hash
end
def to_i
raise_undefined!
raw = @raw
if raw.responds_to?(:to_i)
raw.to_i
else
raise TypeError.new("can't convert #{raw.inspect} to Int32")
end
end
def to_f
raise_undefined!
raw = @raw
if raw.responds_to?(:to_f)
raw.to_f
else
raise TypeError.new("can't convert #{raw.inspect} to Float32")
end
end
# Returns `true` unless this value is `false`, `0`, `nil` or `#undefined?`
def truthy?
!(@raw == false || @raw == 0 || @raw.nil? || undefined?)
end
# Returns `true` if this value is a `Undefined`
def undefined?
@raw.is_a?(Undefined)
end
# Returns `true` if this value is a `Callable`
def callable?
@raw.is_a?(Callable | Callable::Proc)
end
# Returns `true` if this value is a `Number`
def number?
@raw.is_a?(Number)
end
# Returns `true` if the value is a sequence.
# TODO: Improve implementation based on crinja_item
def sequence?
@raw.is_a?(Iterable) || @raw.responds_to?(:each) || string?
end
# Returns `true` if the value is a list (`Array`).
def indexable?
@raw.is_a?(Indexable)
end
# Returns `true` if the value is iteraable.
def iterable?
@raw.is_a?(Iterable)
end
# Returns `true` if the value is a string.
def string?
@raw.is_a?(String | SafeString)
end
# Returns `true` if the object is a mapping (Hash or Crinja::Object).
def mapping?
@raw.is_a?(Hash) || @raw.responds_to?(:crinja_attribute)
end
# Returns `true` if the value is a time object.
def time?
@raw.is_a(Time)
end
# Returns `true` if the value is nil.
def none?
@raw.nil?
end
# Returns true if
def sameas?(other)
raw = @raw
if (raw.is_a?(Reference))
if ((oraw = other.raw).is_a?(Reference))
raw.same?(oraw)
else
false
end
else
!other.raw.is_a?(Reference) && self == other
end
end
UNDEFINED = new(Undefined.new)
end
require "./tuple"
struct Crinja::Value
private class HashTupleIterator
include ::Iterator(Crinja::Tuple)
include IteratorWrapper
def initialize(@iterator : ::Iterator(::Tuple(Value, Value)))
end
def next
tuple = wrapped_next
if tuple.is_a?(::Tuple)
Crinja::Tuple.from tuple
else
stop
end
end
end
end