Skip to content

Commit 16c1fc5

Browse files
committed
variable scope in renamespace
1 parent c3561ea commit 16c1fc5

File tree

4 files changed

+37
-1
lines changed

4 files changed

+37
-1
lines changed

src/ModelingToolkit.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ export Differential, expand_derivatives, @derivatives
158158
export IntervalDomain, ProductDomain, , CircleDomain
159159
export Equation, ConstrainedEquation
160160
export Term, Sym
161+
export SymScope, LocalScope, ParentScope, GlobalScope
161162
export independent_variable, states, parameters, equations, controls, observed, structure
162163
export structural_simplify
163164

src/systems/abstractsystem.jl

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,11 +268,32 @@ function Base.setproperty!(sys::AbstractSystem, prop::Symbol, val)
268268
end
269269
end
270270

271+
abstract type SymScope end
272+
273+
struct LocalScope <: SymScope end
274+
LocalScope(sym::Union{Num, Sym}) = setmetadata(sym, SymScope, LocalScope())
275+
276+
struct ParentScope <: SymScope
277+
parent::SymScope
278+
end
279+
ParentScope(sym::Union{Num, Sym}) = setmetadata(sym, SymScope, ParentScope(getmetadata(value(sym), SymScope, LocalScope())))
280+
281+
struct GlobalScope <: SymScope end
282+
GlobalScope(sym::Union{Num, Sym}) = setmetadata(sym, SymScope, GlobalScope())
283+
271284
function renamespace(namespace, x)
272285
if x isa Num
273286
renamespace(namespace, value(x))
274287
elseif x isa Symbolic
275-
rename(x, renamespace(namespace, getname(x)))
288+
let scope = getmetadata(x, SymScope, LocalScope())
289+
if scope isa LocalScope
290+
rename(x, renamespace(namespace, getname(x)))
291+
elseif scope isa ParentScope
292+
setmetadata(x, SymScope, scope.parent)
293+
else # GlobalScope
294+
x
295+
end
296+
end
276297
else
277298
Symbol(namespace,:₊,x)
278299
end

test/runtests.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using SafeTestsets, Test
22

3+
@safetestset "Varialbe scope tests" begin include("variable_scope.jl") end
34
@safetestset "Symbolic parameters test" begin include("symbolic_parameters.jl") end
45
@safetestset "Parsing Test" begin include("variable_parsing.jl") end
56
@safetestset "Simplify Test" begin include("simplify.jl") end

test/variable_scope.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using ModelingToolkit
2+
using Test
3+
4+
@variables a b c
5+
6+
b = ParentScope(ParentScope(b))
7+
c = GlobalScope(c)
8+
9+
renamed(nss, sym) = nameof(foldr(ModelingToolkit.renamespace, nss, init=sym))
10+
11+
@test renamed([:foo :bar :baz], a) == :foo₊bar₊baz₊a
12+
@test renamed([:foo :bar :baz], b) == :foo₊b
13+
@test renamed([:foo :bar :baz], c) == :c

0 commit comments

Comments
 (0)