From 08be04898f6f75e582aa8645e435b6143c957f33 Mon Sep 17 00:00:00 2001 From: michikawa07 Date: Wed, 29 Mar 2023 12:07:28 +0900 Subject: [PATCH] Update default value of unit_context arg in uparse Nevertheless expanded pkg of Unitful.jl (i.e., UnitfulAtomic.jl) execute Unitful.register(), Unitful.uparse did not recognize these pkgs automaticaly (due to the defaut value of unit_context arg is Unitful only). This commit modified this issue. --- src/user.jl | 9 +++++++-- test/runtests.jl | 12 ++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/user.jl b/src/user.jl index 8df784c9..f6d6e85e 100644 --- a/src/user.jl +++ b/src/user.jl @@ -657,12 +657,12 @@ julia> uparse("1.0*dB") 1.0 dB ``` """ -function uparse(str; unit_context=Unitful) +function uparse(str; unit_context=vcat(Unitful, Unitful.unitmodules)) ex = Meta.parse(str) eval(lookup_units(unit_context, ex)) end -const allowed_funcs = [:*, :/, :^, :sqrt, :√, :+, :-, ://] +const allowed_funcs = [:*, :/, :^, :sqrt, :√, :+, :-, ://, :colon, :(:)] function lookup_units(unitmods, ex::Expr) if ex.head == :call ex.args[1] in allowed_funcs || @@ -684,6 +684,11 @@ function lookup_units(unitmods, ex::Expr) end end return ex + elseif ex.head == :macrocall + if ex.args[1] != Symbol("@u_str") + throw(ArgumentError("Cannot use macro $(ex.args[1]), only use macro @u_str")) + end + return eval(ex) else throw(ArgumentError("Expr head $(ex.head) must equal :call or :tuple")) end diff --git a/test/runtests.jl b/test/runtests.jl index 583c5cd3..16c09209 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1950,10 +1950,22 @@ end # Tests for unit extension modules in unit parsing @test_throws ArgumentError uparse("foo", unit_context=Unitful) +@test uparse("foo") === u"foo" #This work, because default `unit_context` is now `vcat(Unitful, Unitful.unitmodules)` @test uparse("foo", unit_context=FooUnits) === u"foo" @test uparse("foo", unit_context=[Unitful, FooUnits]) === u"foo" @test uparse("foo", unit_context=[FooUnits, Unitful]) === u"foo" +module BazUnits + using Unitful + @unit baz "baz" MyBaz 1u"m" false +end +# Tests unit parsing for unit extension modules in which Unitful.register(BazUnits) was not done +@test_throws ArgumentError uparse("baz", unit_context=Unitful) +@test_throws ArgumentError uparse("baz") #This not work, because BazUnits is not registered to Unitful.unitmodules ( and default `unit_context` argument ) +@test uparse("baz", unit_context=BazUnits) === BazUnits.baz +@test uparse("baz", unit_context=[Unitful, BazUnits]) === BazUnits.baz +@test uparse("baz", unit_context=[BazUnits, Unitful]) === BazUnits.baz + # Test for #272 module OnlyUstrImported import Unitful: @u_str