-
Notifications
You must be signed in to change notification settings - Fork 627
/
test.cr
2551 lines (1935 loc) · 35.2 KB
/
test.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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Examples taken from http://crystal-lang.org/docs/
# Copyright 2012-2018 Manas Technology Solutions.
# Updated on May 17th, 2018 by @faustinoaq.
require "http/server"
server = HTTP::Server.new(8080) do |context|
context.response.content_type = "text/plain"
context.response.print "Hello world! The time is #{Time.now}"
end
puts "Listening on http://0.0.0.0:8080"
server.listen
module HTTP
class RequestHandler
end
end
alias NumericValue = Float32 | Float64 | Int32 | Int64
enum Time::DayOfWeek
end
class Greeting
class_property global_greeting = "Hello world"
@@default_greeting = "Hello world"
def initialize(@custom_greeting = nil)
end
def print_greeting
greeting = @custom_greeting || @@default_greeting
puts greeting
end
end
LUCKY_NUMBERS = [3, 7, 11]
DOCUMENTATION_URL = "http://crystal-lang.org/docs"
module Scorecard
class Parser
def parse(score_text)
begin
score_text.scan(SCORE_PATTERN) do |match|
handle_match(match)
end
rescue err : ParseError
# handle error ...
end
end
end
end
module Money
CURRENCIES = {
"EUR" => 1.0,
"ARS" => 10.55,
"USD" => 1.12,
"JPY" => 134.15,
}
class Amount
getter :currency, :value
def initialize(@currency, @value)
end
end
class CurrencyConversion
def initialize(@amount, @target_currency)
end
def amount
# implement conversion ...
end
end
end
i = 0
while i < 10
proc = ->(x : Int32) do
spawn do
puts(x)
end
end
proc.call(i)
i += 1
end
Fiber.yield
# A buffered channel of capacity 2
channel = Channel(Int32).new(2)
spawn do
channel.send(1)
channel.send(2)
channel.send(3)
end
3.times do |i|
puts channel.receive
end
class MyDictionary(K, V)
end
MyBox.new(1) # :: MyBox(Int32)
MyBox.new("hello") # :: MyBox(String)
module Moo(T)
def t
T
end
end
class Foo(U)
include Moo(U)
def initialize(@value : U)
end
end
foo = Foo.new(1)
foo.t # Int32
class Parent(T)
end
class Int32Child < Parent(Int32)
end
class GenericChild(T) < Parent(T)
end
class Person
end
a = 1
ptr = pointerof(a)
ptr[100_000] = 2 # undefined behaviour, probably a segmentation fault
alias Int32OrString = Int32 | String
alias Int32OrNil = Int32?
alias Int32OrNil_ = Int32 | ::Nil
alias Int32Ptr = Int32*
alias Int32Ptr_ = Pointer(Int32)
alias Int32_8 = Int32[8]
alias Int32_8_ = StaticArray(Int32, 8)
alias Int32StringTuple = {Int32, String}
alias Int32StringTuple_ = Tuple(Int32, String)
alias Int32ToString = Int32 -> String
alias Int32ToString_ = Proc(Int32, String)
alias ProcThatReturnsInt32 = -> Int32
alias Int32AndCharToString = Int32, Char -> String
alias ComplexProc = (Int32 -> Int32) -> String
def foo(x : Int32)
"instance"
end
def foo(x : Int32.class)
"class"
end
foo 1 # "instance"
foo Int32 # "class"
class Parent
end
class Child1 < Parent
end
class Child2 < Parent
end
ary = [] of Parent.class
ary << Child1
ary << Child2
# Same as not specifying a restriction, not very useful
def foo(x : _)
end
# A bit more useful: any two arguments Proc that returns an Int32:
def foo(x : _, _ -> Int32)
end
# alias SameAsInt32 = typeof(2)
# alias Int32OrString_ = typeof(1, "a")
class Person
def initialize(name)
@name = name
@age = 0
end
def name
@name
end
def age
@age
end
end
john = Person.new "John"
peter = Person.new "Peter"
john.name # => "John"
john.age # => 0
peter.name # => "Peter"
class Person
def self.new(name)
instance = Person.allocate
instance.initialize(name)
instance
end
end
if a.is_a?(String)
# here a is a String
end
if b.is_a?(Number)
# here b is a Number
end
a = some_condition ? 1 : "hello"
# a : Int32 | String
if a.is_a?(Number)
# a : Int32
else
# a : String
end
if a.is_a?(String) && b.is_a?(Number)
# here a is a String and b is a Number
end
a.+(b)
struct Vector2
getter x, y
def initialize(@x, @y)
end
def +(other)
Vector2.new(x + other.x, y + other.y)
end
end
v1 = Vector2.new(1, 2)
v2 = Vector2.new(3, 4)
v1 + v2 # => Vector2(@x=4, @y=6)
struct Vector2
def -
Vector2.new(-x, -y)
end
end
v1 = Vector2.new(1, 2)
-v1 # => Vector2(@x=-1, @y=-2)
class MyArray
def [](index)
# ...
end
def [](index1, index2, index3)
# ...
end
def []=(index, value)
# ...
end
end
array = MyArray.new
array[1] # invokes the first method
array[1, 2, 3] # invokes the second method
array[1] = 2 # invokes the third method
array.[](1) # invokes the first method
array.[](1, 2, 3) # invokes the second method
array.[]=(1, 2) # invokes the third method
raise "OH NO!"
raise Exception.new("Some error")
class MyException < Exception
end
begin
raise MyException.new("OH NO!")
rescue ex : MyException
puts "Rescued MyException: #{ex.message}"
end
begin
# ...
rescue ex : MyException | MyOtherException
# only MyException or MyOtherException
rescue
# any other kind of exception
ensure
puts "Cleanup..."
end
def some_method
something_dangerous
rescue
# execute if an exception is raised
end
array = [1, 2, 3]
array[4] # raises because of IndexError
array[4]? # returns nil because of index out of bounds
def some_proc(&block : Int32 -> Int32)
block
end
x = 0
proc = ->(i : Int32) { x += i }
proc = some_proc(&proc)
proc.call(1) # => 1
proc.call(10) # => 11
x # => 11
def add(x, y)
x + y
end
adder = ->add(Int32, Int32)
adder.call(1, 2) # => 3
module Curses
class Window
end
end
Curses::Window.new
module ItemsSize
def size
items.size
end
end
class Items
include ItemsSize
def items
[1, 2, 3]
end
end
items = Items.new
items.size # => 3
module Base64
extend self
def encode64(string)
# ...
end
def decode64(string)
# ...
end
end
Base64.encode64 "hello" # => "aGVsbG8="
if some_condition
a = 1
else
a = "hello"
end
a_as_int = a.as(Int32)
a_as_int.abs # works, compiler knows that a_as_int is Int32
ptr = Pointer(Int32).malloc(1)
ptr.as(Int8*) # :: Pointer(Int8)
array = [1, 2, 3]
# object_id returns the address of an object in memory,
# so we create a pointer with that address
ptr = Pointer(Void).new(array.object_id)
# Now we cast that pointer to the same type, and
# we should get the same value
array2 = ptr.as(Array(Int32))
array2.same?(array) # => true
a = 1
b = a.as(Int32 | Float64)
b # :: Int32 | Float64
ary = [1, 2, 3]
# We want to create an array 1, 2, 3 of Int32 | Float64
ary2 = ary.map { |x| x.as(Int32 | Float64) }
ary2 # :: Array(Int32 | Float64)
ary2 << 1.5 # OK
class Person
def initialize(@name)
end
def name
@name
end
end
a = [] of Person
x = a.map { |f| f.name } # Error: can't infer block return type
a = [] of Person
x = a.map { |f| f.name.as(String) } # OK
Person.new "John"
a = [] of Person
x = a.map { |f| f.name } # OK
loop do
do_something
break if some_condition
end
class Point
def initialize(@x, @y)
end
end
Point.new 1, 2
# 2 x Int32 = 2 x 4 = 8
instance_sizeof(Point) # => 12
a = 1
while a < 5
a += 1
if a == 3
next
end
puts a
end
# The above prints the numbers 2, 4 and 5
lib C
# In C: double cos(double x)
fun cos(value : Float64) : Float64
fun getch : Int32
fun srand(seed : UInt32)
fun exit(status : Int32) : NoReturn
fun printf(format : UInt8*, ...) : Int32
end
C.cos(1.5) # => 0.0707372
C.srand(1_u32)
a = 1
b = 2
C.printf "%d + %d = %d\n", a, b, a + b
lib LibSDL
fun init = SDL_Init(flags : UInt32) : Int32
end
lib LLVMIntrinsics
fun ceil_f32 = "llvm.ceil.f32"(value : Float32) : Float32
end
lib MyLib
fun my_fun(some_size : LibC::SizeT)
end
@[Link("pcre")]
lib LibPCRE
end
lib C
{% if flag?(:x86_64) %}
alias SizeT = UInt64
{% else %}
alias SizeT = UInt32
{% end %}
fun memcmp(p1 : Void*, p2 : Void*, size : C::SizeT) : Int32
end
lib X
enum SomeEnum
Ten = 10
Twenty = 10 * 2
ThirtyTwo = 1 << 5
end
end
lib X
enum SomeEnum
A = 1_u32
end
end
X::SomeEnum::Zero # => 0_i8
X::SomeEnum::Two # => 2_i8
lib X
fun callback(f : Int32 -> Int32)
end
f = ->(x : Int32) { x + 1 }
X.callback(f)
X.callback ->(x) { x + 1 }
X.callback nil
lib LibFoo
fun store_callback(callback : ->)
fun execute_callback
end
LibFoo.store_callback ->{ raise "OH NO!" }
LibFoo.execute_callback
lib LibFoo
fun store_callback(callback : ->)
@[Raises]
fun execute_callback
end
@[Link("pcre")]
lib PCRE
INFO_CAPTURECOUNT = 2
end
PCRE::INFO_CAPTURECOUNT # => 2
lib U
# In C:
#
# union IntOrFloat {
# int some_int;
# double some_float;
# };
union IntOrFloat
some_int : Int32
some_float : Float64
end
end
value = U::IntOrFloat.new
value = uninitialized U::IntOrFlaot
value.some_int # => some garbage value
value = U::IntOrFloat.new
value.some_int = 1
value.some_int # => 1
value.some_float # => 4.94066e-324
def change_it(value)
value.some_int = 1
end
value = U::IntOrFloat.new
change_it value
value.some_int # => 0
lib C
# In C:
#
# struct TimeZone {
# int minutes_west;
# int dst_time;
# };
struct TimeZone
minutes_west : Int32
dst_time : Int32
end
end
lib C
# This is a forward declaration
struct Node
end
struct Node
node : Node*
end
end
tz = C::TimeZone.new
tz = uninitialized C::TimeZone
tz.minutes_west # => some garbage value
tz = C::TimeZone.new
tz.minutes_west = 1
tz.minutes_west # => 1
tz = C::TimeZone.new minutes_west: 1, dst_time: 2
tz.minutes_west # => 1
tz.dst_time # => 2
def change_it(tz)
tz.minutes_west = 1
end
tz = C::TimeZone.new
change_it tz
tz.minutes_west # => 0
lib C
$errno : Int32
end
C.errno # => some value
C.errno = 0
C.errno # => 0
lib C
@[ThreadLocal]
$errno : Int32
end
lib C
fun waitpid(pid : Int32, status_ptr : Int32*, options : Int32) : Int32
end
status_ptr = uninitialized Int32
C.waitpid(pid, pointerof(status_ptr), options)
C.waitpid(pid, out status_ptr, options)
lib X
type CInt = Int32
end
{% if flag?(:x86_64) %}
# some specific code for 64 bits platforms
{% else %}
# some specific code for non-64 bits platforms
{% end %}
{% if flag?(:linux) && flag?(:x86_64) %}
# some specific code for linux 64 bits
{% end %}
lib C
{% if flag?(:linux) && flag?(:x86_64) %}
struct SomeStruct
some_field : Int32
end
{% else %}
struct SomeStruct
some_field : Int64
end
{% end %}
end
# Assigns to a local variable
local = 1
# Assigns to a global property
class Global
class_property global1 = 1
class_getter global2 = 2
class_setter global3 = 3
# Fails on nil
class_property! global4 = 4
class_getter! global5 = 5
class_setter! global6 = 6
end
class Testing
# Assigns to an instance variable
@instance = 2
# Assigns to a class variable
@@class = 3
end
local += 1 # same as: local = local + 1
# The above is valid with these operators:
# +, -, *, /, %, |, &, ^, **, <<, >>
local ||= 1 # same as: local || (local = 1)
local &&= 1 # same as: local && (local = 1)
# A setter
person.name=("John")
# The above can be written as:
person.name = "John"
# An indexed assignment
objects.[]=(2, 3)
# The above can be written as:
objects[2] = 3
# Not assignment-related, but also syntax sugar:
objects.[](2, 3)
# The above can be written as:
objects[2, 3]
person.age += 1 # same as: person.age = person.age + 1
person.name ||= "John" # same as: person.name || (person.name = "John")
person.name &&= "John" # same as: person.name && (person.name = "John")
objects[1] += 2 # same as: objects[1] = objects[1] + 2
objects[1] ||= 2 # same as: objects[1]? || (objects[1] = 2)
objects[1] &&= 2 # same as: objects[1]? && (objects[1] = 2)
alias PInt32 = Pointer(Int32)
ptr = PInt32.malloc(1) # : Pointer(Int32)
alias RecArray = Array(Int32) | Array(RecArray)
ary = [] of RecArray
ary.push [1, 2, 3]
ary.push ary
ary # => [[1, 2, 3], [...]]
module Json
alias Type = Nil |
Bool |
Int64 |
Float64 |
String |
Array(Type) |
Hash(String, Type)
end
a = 1
if a > 0
a = 10
end
a # => 10
b = 1
if b > 2
b = 10
else
b = 20
end
b # => 20
if some_condition
do_something
elsif some_other_condition
do_something_else
else
do_that
end
a = 1
if some_condition
a = "hello"
else
a = true
end
# a : String | Bool
b = 1
if some_condition
b = "hello"
end
# b : Int32 | String
if some_condition
c = 1
else
c = "hello"
end
# c : Int32 | String
if some_condition
d = 1
end
# d : Int32 | Nil
a = 1
if some_condition
a = "hello"
# a : String
a.size
end
# a : String | Int32
if some_condition
e = 1
else
e = "hello"
# e : String
return
end
# e : Int32
enum Color : UInt8
Red # 0
Green # 1
Blue = 5 # overwritten to 5
Yellow # 6 (5 + 1)
def red?
self == Color::Red
end
end
Color::Red.value # :: UInt8
@[Flags]
enum IOMode
Read # 1
Write # 2
Async # 4
end
IOMode::None.value # => 0
IOMode::All.value # => 7
puts(Color::Red) # prints "Red"
puts(IOMode::Write | IOMode::Async) # prints "Write, Async"
puts Color.new(1) # => prints "Green"
puts Color.new(10) # => prints "10"
Color::Red.red? # => true
Color::Blue.red? # => false
def paint(color : Color)
case color
when Color::Red
# ...
else
# Unusual, but still can happen
raise "unknown color: #{color}"
end
end
paint Color::Red
def paint(color : Symbol)
case color
when :red
# ...
else
raise "unknown color: #{color}"
end
end
paint :red
name = "Crystal"
age = 1
flower = "Tulip"
# At this point 'flower' is a String
flower = 1
# At this point 'flower' is an Int32
class Foo
def finalize
# Invoked when Foo is garbage-collected
puts "Bye bye from #{self}!"
end
end
# Prints "Bye bye ...!" for ever
loop do
Foo.new
end
# Defines a method in the program
def add(x, y)
x + y
end
# Invokes the add method in the program
add(1, 2) # => 3
def even?(num)
if num % 2 == 0
return true
end
return false
end
def add(x, y)
x + y
end
class Foo
def bar
# invokes the program's add method
add(1, 2)
# invokes Foo's baz method
baz(1, 2)
end
def baz(x, y)
x * y
end
end
def baz(x, y)
x + y
end
class Foo
def bar
baz(4, 2) # => 2
::baz(4, 2) # => 6
end
def baz(x, y)
x - y
end
end
x = 1
def add(y)
x + y # error: undefined local variable or method 'x'
end
add(2)
add 1, 2 # same as add(1, 2)
class Counter
@@instances = 0
def initialize
@@instances += 1
end
def self.instances
@@instances
end
end
Counter.instances # => 0
Counter.new
Counter.new
Counter.new
Counter.instances # => 3
class Counter
def self.increment