-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathswitch_fallout.jl
More file actions
68 lines (53 loc) · 1.23 KB
/
switch_fallout.jl
File metadata and controls
68 lines (53 loc) · 1.23 KB
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
# switch statement (with fallout)
macro switch(value, block)
@gensym value_sym
clauses, statements = switch(value_sym, block)
:(for i in 1:1
let $(esc(value_sym)) = $value
$(clauses)
$(esc(statements))
end
end)
end
@metafunction switch(value, begin :L{:case}(x); :?{xs}; :L{:case}(y); *{ys} end) begin
@gensym label
nextclauses, nextstatements = switch(value, quote :case($y); $(ys...) end)
clauses = switch_clause(value, x, label, nextclauses)
statements = switch_statements(xs, label, nextstatements)
clauses, statements
end
@metafunction switch(value, begin :L{:case}(x); *{xs} end) begin
@gensym label
clauses = switch_clause(value, x, label)
statements = switch_statements(xs, label)
clauses, statements
end
switch_clause(value, x, label, nextclauses=nothing) = quote
if $value == $x
@goto $label
else
$nextclauses
end
end
switch_statements(statements, label, nextstatements=nothing) = quote
@label $label
$(statements...);
$(nextstatements)
end
# usage
r = 0
a = 2
@switch a begin
:case(1);
r = 1
break
:case(2);
r = 2
:case(3);
r = 3
end
import Base.Test.@test
if a in [1,2]
@test a != 1 || r == 1
@test a != 2 || r == 3
end