Skip to content

Commit e26075f

Browse files
committed
refactor: use the t defined in the module
`t` is now available in three flavours. Thus, allow a downstream package to import the appropriate one, and use that to define the mtk-models.
1 parent 4db0053 commit e26075f

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

src/systems/model_parsing.jl

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ function _model_macro(mod, name, expr, isconnector)
9292

9393
iv = get(dict, :independent_variable, nothing)
9494
if iv === nothing
95-
iv = dict[:independent_variable] = variable(:t)
95+
iv = dict[:independent_variable] = get_t(mod, :t)
9696
end
9797

9898
push!(exprs.args, :(push!(equations, $(eqs...))))
@@ -199,7 +199,7 @@ function parse_variable_def!(dict, mod, arg, varclass, kwargs, where_types;
199199
parse_variable_def!(dict, mod, a, varclass, kwargs, where_types; def, type)
200200
end
201201
Expr(:call, a, b) => begin
202-
var = generate_var!(dict, a, b, varclass; indices, type)
202+
var = generate_var!(dict, a, b, varclass, mod; indices, type)
203203
update_kwargs_and_metadata!(dict, kwargs, a, def, indices, type, var,
204204
varclass, where_types)
205205
(var, def)
@@ -280,11 +280,10 @@ function generate_var!(dict, a, varclass;
280280
generate_var(a, varclass; indices, type)
281281
end
282282

283-
function generate_var!(dict, a, b, varclass;
283+
function generate_var!(dict, a, b, varclass, mod;
284284
indices::Union{Vector{UnitRange{Int}}, Nothing} = nothing,
285285
type = Real)
286-
# (type isa Nothing && type = Real)
287-
iv = generate_var(b, :variables)
286+
iv = b == :t ? get_t(mod, b) : generate_var(b, :variables)
288287
prev_iv = get!(dict, :independent_variable) do
289288
iv
290289
end
@@ -306,6 +305,20 @@ function generate_var!(dict, a, b, varclass;
306305
var
307306
end
308307

308+
# Use the `t` defined in the `mod`. When it is unavailable, generate a new `t` with a warning.
309+
function get_t(mod, t)
310+
try
311+
get_var(mod, t)
312+
catch e
313+
if e isa UndefVarError
314+
@warn("Could not find a predefined `t` in `$mod`; generating a new one within this model.\nConsider defining it or importing `t` (or `t_nounits`, `t_unitful` as `t`) from ModelingToolkit.")
315+
variable(:t)
316+
else
317+
throw(e)
318+
end
319+
end
320+
end
321+
309322
function parse_default(mod, a)
310323
a = Base.remove_linenums!(deepcopy(a))
311324
MLStyle.@match a begin

test/precompile_test/ModelParsingPrecompile.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
module ModelParsingPrecompile
22

33
using ModelingToolkit, Unitful
4+
using ModelingToolkit: t
45

56
@mtkmodel ModelWithComponentArray begin
67
@constants begin

0 commit comments

Comments
 (0)