Skip to content

Commit

Permalink
Merge pull request #133 from serenity4/trymatch
Browse files Browse the repository at this point in the history
Implement `@trymatch`
  • Loading branch information
thautwarm authored Dec 29, 2021
2 parents ebfbeae + f3840bc commit 01cdf56
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 9 deletions.
39 changes: 30 additions & 9 deletions src/MatchImpl.jl
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module MatchImpl
export is_enum,
pattern_uncall, pattern_unref, pattern_unmacrocall, @switch, @tryswitch, @match, Where, gen_match, gen_switch
pattern_uncall, pattern_unref, pattern_unmacrocall, @switch, @tryswitch, @match, @trymatch, Where, gen_match, gen_switch
export Q
import MLStyle
using MLStyle: mlstyle_report_deprecation_msg!
Expand Down Expand Up @@ -405,14 +405,10 @@ It is equivalent to
"""
macro tryswitch(val, ex)
@assert Meta.isexpr(ex, :block)
insert_case = length(ex.args) >= 2 || begin
case, line = ex.args[end-2:end]
Meta.isexpr(case, [:macrocall], 3) &&
case.args[1] == Symbol("@case") &&
case.args[3] == :_
end
insert_case && push!(ex.args, Expr(:macrocall, Symbol("@case"), __source__, :_), :nothing)
:($(esc(:($(@__MODULE__).@switch $val $ex))))
push!(ex.args, Expr(:macrocall, case_sym, __source__, :_), :nothing)
res = gen_switch(val, ex, __source__, __module__)
res = init_cfg(res)
esc(res)
end
@specialize
function gen_switch(val, ex, __source__::LineNumberNode, __module__::Module)
Expand Down Expand Up @@ -578,6 +574,31 @@ macro match(val, tbl)
res = init_cfg(res)
esc(res)
end
"""
@trymatch <item> begin
<pattern> => <result>
<pattern> => <result>
end
Very similar to [`@match`](@ref), except that a failure to match does nothing instead of throwing a "match non-exhaustive" error.
It is equivalent to
```julia
@match <item> begin
<pattern> => <result>
<pattern> => <result>
_ => nothing
end
```
"""
macro trymatch(val, tbl)
Meta.isexpr(tbl, :block) || (tbl = Expr(:block, tbl))
push!(tbl.args, :(_ => nothing))
res = gen_match(val, tbl, __source__, __module__)
res = init_cfg(res)
esc(res)
end
@specialize

function gen_match(val, tbl, __source__::LineNumberNode, __module__::Module)
Expand Down
7 changes: 7 additions & 0 deletions test/match.jl
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,11 @@
@test (@match 1 1 => 2) == 2
@test (@match [1, 2, 3] [hd, tl...] => (hd, tl)) == (1, [2,3])
end

@testset "trymatch" begin
val = @trymatch true begin
::Int => 1
end
@test val === nothing
end
end

0 comments on commit 01cdf56

Please sign in to comment.