-
Notifications
You must be signed in to change notification settings - Fork 30
/
fix-demo.jl.diff
55 lines (46 loc) · 2.14 KB
/
fix-demo.jl.diff
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
diff --git a/demo.jl b/demo.jl
index cc3fc4a7..9c76524b 100644
--- a/demo.jl
+++ b/demo.jl
@@ -3,11 +3,20 @@
# JET can find simple errors:
-fib(n) = n ≤ 2 ? n : fib(n-1) + fib(n-2)
+function fib(n::T) where {T<:Number}
+ cache = Dict(zero(T)=>zero(T), one(T)=>one(T))
+ return _fib(n, cache)
+end
+_fib(n, cache) = if haskey(cache, n)
+ cache[n]
+else
+ cache[n] = _fib(n-1, cache) + _fib(n-2, cache)
+end
-fib(1000) # => never terminates
-fib(m) # => ERROR: UndefVarError: `m` not defined
-fib("1000") # => ERROR: MethodError: no method matching isless(::String, ::Int64)
+fib(BigInt(1000)) # will terminate
+m = 1000
+fib(m)
+fib(parse(Int, "1000"))
# JET supports all Julia language features:
@@ -22,19 +31,19 @@ end
# it can analyze code with macros
@inline bar(n::T) where {T<:Number} = n < 0 ? zero(T) : one(T)
-@inline bar(v::Ty{T}) where {T<:Number} = bar(v.fdl) # typo "fdl"
+@inline bar(v::Ty{T}) where {T<:Number} = bar(v.fld) # typo fixed
@inline bar(v::Ty) = bar(convert(Number, v.fld))
-foo(1.2) # => ERROR: type Ty has no field fdl
-foo("1") # => ERROR: MethodError: Cannot `convert` an object of type String to an object of type Number
+foo(1.2)
+foo('1') # `'1'::Char` can be converted to `0x00000031::UInt32`
# even staged code can be analyzed
# (adapted from https://github.com/JuliaLang/julia/blob/9f665c19e076ab37cbca2d0cc99283b82e99c26f/base/namedtuple.jl#L253-L264)
-@generated function badmerge(a::NamedTuple{an}, b::NamedTuple{bn}) where {an, bn}
+@generated function goodmerge(a::NamedTuple{an}, b::NamedTuple{bn}) where {an, bn}
names = Base.merge_names(an, bn)
types = Base.merge_types(names, a, b)
- vals = Any[ :(getfield($(Base.sym_in(names[n], bn) ? :b : :a), $(names[n]))) for n in 1:length(names) ] # missing quote, just ends up with under vars
+ vals = Any[ :(getfield($(Base.sym_in(names[n], bn) ? :b : :a), $(QuoteNode(names[n])))) for n in 1:length(names) ] # names quoted, should work as expected
:( NamedTuple{$names,$types}(($(vals...),)) )
end
-badmerge((x=1,y=2), (y=3,z=1)) # => ERROR: UndefVarError: `x` not defined
+goodmerge((x=1,y=2), (y=3,z=1))