Skip to content

Commit 9b16d71

Browse files
authored
Merge pull request #175 from MilesCranmer/dev
Fix `@mlj_model` parsing bug
2 parents d33265f + 2f376b0 commit 9b16d71

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

src/model_def.jl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,12 +62,12 @@ function _process_model_def(modl, ex)
6262
if line.head == :(=) # assignment for default
6363
default = line.args[2]
6464
# if a constraint is given (value::constraint)
65-
if default isa Expr && length(default.args) > 1
65+
if default isa Expr && default.head == :(::)
6666
constraints[param] = default.args[2]
6767
# now discard the constraint to keep only the value
6868
default = default.args[1]
6969
end
70-
defaults[param] = default # this will be a value not an expr
70+
defaults[param] = default
7171

7272
# name or name::Type (for the constructor)
7373
ex.args[3].args[i] = line.args[1]

test/model_def.jl

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,34 @@ end
151151
@test Cc().a === nothing
152152
@test Cd().a === missing
153153
end
154+
155+
@testset "Expression defaults" begin
156+
# Should work with and without constraint:
157+
@mlj_model mutable struct Foo1
158+
a::Vector{Int} = [1, 2, 3]
159+
end
160+
@test Foo1().a == [1, 2, 3]
161+
@mlj_model mutable struct Foo2
162+
a::Vector{Int} = [1, 2, 3]::(true)
163+
end
164+
@test Foo2().a == [1, 2, 3]
165+
166+
# Constraints applied
167+
@mlj_model mutable struct Foo3
168+
a::Vector{Int} = [1, 2, 3]::(all(>(0), _))
169+
end
170+
@test redirect_stderr(devnull) do
171+
Foo3(; a = [-1]).a == [1, 2, 3]
172+
end
173+
174+
# Negative number:
175+
@mlj_model mutable struct Foo4
176+
a::Float64 = -1.0
177+
end
178+
@test Foo4().a === -1.0
179+
@mlj_model mutable struct Foo5
180+
a::Float64 = (-1.0)::(true)
181+
end
182+
@test Foo5().a == -1.0
183+
184+
end

0 commit comments

Comments
 (0)