diff --git a/docs/src/utilities.md b/docs/src/utilities.md index 6ac3243..9f8d918 100644 --- a/docs/src/utilities.md +++ b/docs/src/utilities.md @@ -46,6 +46,7 @@ MacroTools.@q MacroTools.@qq MacroTools.isexpr MacroTools.rmlines +MacroTools.rmdocs MacroTools.unblock MacroTools.namify MacroTools.inexpr diff --git a/src/utils.jl b/src/utils.jl index 599281a..1d1619f 100644 --- a/src/utils.jl +++ b/src/utils.jl @@ -1,4 +1,4 @@ -export @esc, isexpr, isline, iscall, rmlines, unblock, block, inexpr, namify, isdef, +export @esc, isexpr, isline, iscall, rmlines, rmdocs, unblock, block, inexpr, namify, isdef, longdef, shortdef, @expand, makeif, prettify, combinedef, splitdef, splitarg, combinearg macro public(ex) @@ -122,6 +122,43 @@ end striplines(ex) = prewalk(rmlines, ex) +""" + rmdocs(x) + +Remove the documentation macros from the expression. + +### Examples + +To work with nested blocks: + +```julia +prewalk(rmdocs, ex) +``` + +See also: [`rmlines`](@ref) +""" +rmdocs(x) = x +function rmdocs(ex::Expr) + if ex.head == :macrocall + m = ex.args[1] + if isa(m, GlobalRef) && m.mod == Core && m.name == Symbol("@doc") + for i ∈ 2:length(ex.args) + arg = ex.args[i] + if !isline(arg) && !isnothing(arg) + doc = arg + if i < length(ex.args) + return ex.args[i + 1] + end + end + end + return nothing + end + end + return ex +end + +stripdocs(ex) = prewalk(rmdocs, ex) + """ unblock(expr) @@ -592,6 +629,12 @@ end prettify(ex) Makes generated code generaly nicer to look at. + +# Keywords +- `lines::Bool=false`: whether to preserve line number nodes +- `alias::Bool=true`: whether to replace gensyms with animal names +- `docs::Bool=false`: whether to preserve docstrings """ -prettify(ex; lines = false, alias = true) = - ex |> (lines ? identity : striplines) |> flatten |> unresolve |> resyntax |> (alias ? alias_gensyms : identity) +prettify(ex; lines=false, alias=true, docs=false) = + ex |> (lines ? identity : striplines) |> (docs ? identity : stripdocs) |>flatten |> + unresolve |> resyntax |> (alias ? alias_gensyms : identity) diff --git a/test/utils.jl b/test/utils.jl index 5aed8dd..34621f2 100644 --- a/test/utils.jl +++ b/test/utils.jl @@ -38,6 +38,27 @@ end @test isdef(:(function (y) y - 4 end)) end +@testset "rmlines & rmdocs" begin + ex1 = quote + foo(x) = x + 1 + end + ex2 = quote + "My own documentation" + foo(x) = x + 1 + + "This is a docstring" + bar(x) = x + 2 + end + ex3 = quote + foo(x) = x + 1 + bar(x) = x + 2 + end + @test !any(isline, MacroTools.striplines(ex1).args) + @test !any(isline, MacroTools.striplines(ex2).args) + @test MacroTools.striplines(MacroTools.stripdocs(ex2)) == MacroTools.striplines(ex3) +end + + @testset "flatten" begin @test flatten(quote begin; begin; f(); g(); end; begin; h(); end; f(); end; end) |> striplines == quote f(); g(); h(); f() end |> striplines end