File: crystal

package info (click to toggle)
ruby-rouge 4.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,836 kB
  • sloc: ruby: 38,168; sed: 2,071; perl: 152; makefile: 8
file content (698 lines) | stat: -rw-r--r-- 10,809 bytes parent folder | download | duplicates (2)
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
# Examples taken from http://crystal-lang.org/docs/
# Copyright 2012-2018 Manas Technology Solutions.
# Based on the sample in the Pygments project (github.com/pygments/pygments)

## Constants

LUCKY_NUMBERS     = [3, 7, 11]
DOCUMENTATION_URL = "http://crystal-lang.org/docs"

## Assignments

i = 0
items = Items.new
channel = Channel(Int32).new(2)
a = [] of Person
hash = {} of Int32 => String
nest = [1, ["b", [:c, ['d']]]]

## Require statements

require "http/server"

## Blocks

x = a.map { |f| f.name } # Error: can't infer block return type

spawn do
  channel.send(1)
  channel.send(2)
  channel.send(3)
end

3.times do |i|
  puts channel.receive
end

server = HTTP::Server.new(8080) do |context|
  context.response.content_type = "text/plain"
  context.response.print "Hello world! The time is #{Time.now}"
end

## Loops

while i < 10
  proc = ->(x : Int32) do
    spawn do
      puts(x)
    end
  end
  proc.call(i)
  i += 1
end

until some_condition
  do_this
end

## Module definitions

module HTTP
  class RequestHandler
  end
end

module Base64
  extend self

  def encode64(string)
    # ...
  end
end

module Moo(T)
  def t
    T
  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

## Class definitions

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

class MyArray
  def [](index)
    # ...
  end

  def [](index1, index2, index3)
    # ...
  end

  def []=(index, value)
    # ...
  end
end

class MyDictionary(K, V)
end

class Foo(U)
  include Moo(U)

  def initialize(@value : U)
  end
end

class Int32Child < Parent(Int32)
end

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

abstract class Animal
  # Makes this animal talk
  abstract def talk
end

## Struct definitions

struct Vector2
  getter x, y

  def initialize(@x, @y)
  end

  def +(other)
    Vector2.new(x + other.x, y + other.y)
  end
end

struct Vector2
  def -
    Vector2.new(-x, -y)
  end
end

## Library definitions

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

@[Link("pcre")]
lib LibPCRE
end

lib LibFoo
  fun store_callback(callback : ->)

  @[Raises]
  fun execute_callback
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 U
  union IntOrFloat
    some_int : Int32
    some_float : Float64
  end
end

## Aliase declarations

alias NumericValue = Float32 | Float64 | Int32 | Int64
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

## Enum declarations

enum Time::DayOfWeek
end

enum Color : UInt8
  Red        # 0
  Green      # 1
  Blue   = 5 # overwritten to 5
  Yellow     # 6 (5 + 1)

  def red?
    self == Color::Red
  end
end

@[Flags]
enum IOMode
  Read  # 1
  Write # 2
  Async # 4
end

## Method definitions

def foo(x : Int32)
  "instance"
end

def foo(x : Int32.class)
  "class"
end

def foo(x : _)
end

def foo(x : _, _ -> Int32)
end

def some_proc(&block : Int32 -> Int32)
  block
end

def twice(&block)
  yield
  yield
end


def paint(color : Color)
  case color
  when Color::Red
    # ...
  else
    # Unusual, but still can happen
    raise "unknown color: #{color}"
  end
end

def counter
  x = 0
  ->{ x += 1; x }
end

## Method calls

puts "Listening on http://0.0.0.0:8080"
server.listen
Fiber.yield
Curses::Window.new
foo 1     # "instance"
foo Int32 # "class"
a.+(b)
C.printf "%d + %d = %d\n", a, b, a + b

array[1]       # invokes the first method
array[1, 2, 3] # invokes the second method
array[1] = 2   # invokes the third method
array[4]? # returns nil because of index out of bounds
array.[](1)       # invokes the first method
array.[](1, 2, 3) # invokes the second method
array.[]=(1, 2)   # invokes the third method

## Operators

john == another_john # => true

ary << Child1
ary << Child2

local += 1 # same as: local = local + 1
local ||= 1 # same as: local || (local = 1)
local &&= 1 # same as: local && (local = 1)

x..y  # an inclusive range, in mathematics: [x, y]
x...y # an exclusive range, in mathematics: [x, y)

## Conditionals

a = some_condition ? 1 : "hello"
a = 1 > 2 ? 3 : 4

if some_condition
  a = 1
else
  a = "hello"
end

if a.is_a?(String)
  # here a is a String
end

if a.is_a?(Number)
  # a : Int32
else
  # a : String
end

if some_condition
  do_something
elsif some_other_condition
  do_something_else
else
  do_that
end

if a.is_a?(String) && b.is_a?(Number)
  # here a is a String and b is a Number
end

unless some_condition
  then_expression
else
  else_expression
end

a = 2 if some_condition
close_door unless door_closed?

case exp
when value1, value2
  do_something
when value3
  do_something_else
else
  do_another_thing
end

## Exceptions

raise "OH NO!"
raise Exception.new("Some error")

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

## Procs

proc = ->(i : Int32) { x += i }
proc = some_proc(&proc)
proc.call(1)  # => 1
adder = ->add(Int32, Int32)
adder.call(1, 2) # => 3
twice &proc
twice &->{ puts "Hello" }

## Macros

{% 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 %}

{% if env("TEST") %}
  puts "We are in test mode"
{% end %}

macro fresh_vars_sample(*names)
  # First declare vars
  {% for name, index in names %}
    print "Declaring: ", "%name{index}", '\n'
    %name{index} = {{index}}
  {% end %}

  # Then print them
  {% for name, index in names %}
    print "%name{index}: ", %name{index}, '\n'
  {% end %}
end

macro method_missing(name, args, block)
  print "Got ", {{name.id.stringify}}, " with ", {{args.size}}, " arguments", '\n'
end

macro define_method(name, content)
  def {{name}}
    {% if content == 1 %}
      "one"
    {% else %}
      {{content}}
    {% end %}
  end
end

## Numbers

1.0     # Float64
1.0_f32 # Float32
1_f32   # Float32

1e10   # Float64
1.5e10 # Float64
1.5e-7 # Float64

+1.3 # Float64
-0.5 # Float64

1_000_000.111_111 # better than 1000000.111111

1 # Int32

1_i8  # Int8
1_i16 # Int16
1_i32 # Int32
1_i64 # Int64

1_u8  # UInt8
1_u16 # UInt16
1_u32 # UInt32
1_u64 # UInt64

+10 # Int32
-20 # Int32

2147483648          # Int64
9223372036854775808 # UInt64

1_000_000 # better than 1000000

0b1101 # == 13

0o123 # == 83

0xFE012D # == 16646445
0xfe012d # == 16646445

## Regular expressions

foo_or_bar = /foo|bar/
heeello = /h(e+)llo/
integer = /\d+/
r = /foo/imx
slash = /\//
r = %r(regex with slash: /)

## Strings

"hello world"

"\"" # double quote
"\\" # backslash
"\e" # escape
"\f" # form feed
"\n" # newline
"\r" # carriage return
"\t" # tab
"\v" # vertical tab

"\101" # == "A"
"\123" # == "S"
"\12"  # == "\n"
"\1"   # string with one character with code point 1

"\u0041" # == "A"

"\u{41}"    # == "A"
"\u{1F52E}" # == "🔮"
"あ"

"hello
      world" # same as "hello\n      world"

"hello " \
"world, " \
"no newlines" # same as "hello world, no newlines"

"hello \
     world, \
     no newlines" # same as "hello world, no newlines"

# Supports double quotes and nested parenthesis
%(hello ("world")) # same as "hello (\"world\")"

# Supports double quotes and nested brackets
%[hello ["world"]] # same as "hello [\"world\"]"

# Supports double quotes and nested curlies
%{hello {"world"}} # same as "hello {\"world\"}"

# Supports double quotes and nested angles
%<hello <"world">> # same as "hello <\"world\">"

## Heredoc strings

<<-XML
<parent>
  <child />
</parent>
XML

<<-STRING
  Hello
    world
  STRING

## Characters

'a'
'z'
'0'
'_'

'\'' # single quote
'\\' # backslash
'\e' # escape
'\f' # form feed
'\n' # newline
'\r' # carriage return
'\t' # tab
'\v' # vertical tab

"\101" # == 'A'
"\123" # == 'S'
"\12"  # == '\n'
"\1"   # code point 1

'\u0041' # == 'A'

'\u{41}'    # == 'A'
'\u{1F52E}' # == '🔮'

## Symbols

:hello
:good_bye

# With spaces and symbols
:"symbol with spaces"

# Ending with question and exclamation marks
:question?
:exclamation!

# For the operators
:+
:-
:*
:/
:==
:<
:<=
:>
:>=
:!
:!=
:=~
:!~
:&
:|
:^
:~
:**
:>>
:<<
:%
:[]
:[]?
:[]=
:<=>
:===

## Hashes

{1 => 2, 3 => 4}   # Hash(Int32, Int32)
{1 => 2, 'a' => 3} # Hash(Int32 | Char, Int32)
{} of Int32 => Int32 # same as Hash(Int32, Int32).new
{key1: 'a', key2: 'b'} # Hash(Symbol, Char)
{"key1": 'a', "key2": 'b'} # Hash(String, Char)

MyType{"foo" => "bar"}
MyType(String, String){"foo" => "bar"}

## Tuples

tuple = {1, "hello", 'x'} # Tuple(Int32, String, Char)
tuple[0]                  # => 1       (Int32)
tuple[1]                  # => "hello" (String)
tuple[2]                  # => 'x'     (Char)

## Arrays

[1, 2, 3]         # Array(Int32)
[1, "hello", 'x'] # Array(Int32 | String | Char)

[] of Int32 # same as Array(Int32).new

%w(one two three) # ["one", "two", "three"]
%i(one two three) # [:one, :two, :three]

## Keywords

nil
true  # A Bool that is true
false # A Bool that is false

# Unicode support
class ViệtNam
  def chào(buổi)
    câu_chào = {sáng: "Chào buổi sáng", chiều: "Chào buổi chiều"}
    puts câu_chào[buổi]
  end
end

việt_nam = ViệtNam.new
việt_nam.chào(:sáng)