制作宏以将功能标记为已弃用 用于测试:

问题描述

在我先前的question中,我发现标准库(Julia v1.5)宏@deprecate用于替换其他函数

我想制作一个mark_deprecated,将其应用于函数时会产生以下效果

  1. 调用目标函数时(如果可能,仅在第一次调用它时)打印一个自定义的弃用警告。
  2. 修改功能的文档(可查看为julia>? function_name),以包含弃用警告。

当然,稍后可能会包含许多其他方便的选项,例如指定替换功能功能,产生错误而不是警告的选项等。

我主要是在Julia元编程中进行此练习,到目前为止,我的经验为零(有点担心这作为第一个任务可能太难了)。

试图了解@deprecate

第一步,我看了当前的标准库@deprecate宏。内容如下:

# julia v1.5
# quoted from deprecated.jl,included by Base.jl

macro deprecate(old,new,ex=true)
    Meta = Expr(:Meta,:noinline)
    if isa(old,Symbol)
        oldname = Expr(:quote,old)
        newname = Expr(:quote,new)
        Expr(:toplevel,ex ? Expr(:export,esc(old)) : nothing,:(function $(esc(old))(args...)
                  $Meta
                  depwarn($"`$old` is deprecated,use `$new` instead.",Core.Typeof($(esc(old))).name.mt.name)
                  $(esc(new))(args...)
              end))
    elseif isa(old,Expr) && (old.head === :call || old.head === :where)
        remove_linenums!(new)
        oldcall = sprint(show_unquoted,old)
        newcall = sprint(show_unquoted,new)
        # if old.head is a :where,step down one level to the :call to avoid code duplication below
        callexpr = old.head === :call ? old : old.args[1]
        if callexpr.head === :call
            if isa(callexpr.args[1],Symbol)
                oldsym = callexpr.args[1]::Symbol
            elseif isa(callexpr.args[1],Expr) && callexpr.args[1].head === :curly
                oldsym = callexpr.args[1].args[1]::Symbol
            else
                error("invalid usage of @deprecate")
            end
        else
            error("invalid usage of @deprecate")
        end
        Expr(:toplevel,esc(oldsym)) : nothing,:($(esc(old)) = begin
                  $Meta
                  depwarn($"`$oldcall` is deprecated,use `$newcall` instead.",Core.Typeof($(esc(oldsym))).name.mt.name)
                  $(esc(new))
              end))
    else
        error("invalid usage of @deprecate")
    end
end

我试图理解这件事(如果您了解宏,则无需阅读):

  • documentation中对:Meta内容进行了解释。
  • 从不使用宏内的变量oldnamenewname。我认为这是由于开发人员的疏忽所致(相对于尽管未使用变量,声明的作用也不明显)。我将其删除
  • 我不确定如何处理a(...) where B表达式(这样的表达式会进入顶层elseif块)。现在不用担心这部分。似乎where表达式无论如何都被剥离了。与表达式中的:curly括号相同。在任何情况下,似乎函数符号(oldsym)都是从表达式(第一个参数)中提取的。
  • 我不知道Base.show_unquoted到底能做什么。好像它会将表达式“打印”成字符串只是为了输出,所以我不必担心细节。
  • 宏的主要内容当然是返回的Expr。它断言它是在顶级评估的。我不在乎的出口商品。
  • 我不知道Core.Typeof($(esc(oldsym))).name.mt.name是什么。它似乎是函数的实际Symbol(与包含符号的字符串相反)。 Core.Typeof似乎与typeof相同。您可以执行typeof(some_function).name.mt.name并从mt::Core.MethodTable中取出符号。有趣的是,Tab-Completion似乎不适用于这些低级别的数据结构及其字段。

朝向我的宏

试图to窃上述内容

# julia v1.5
module MarkDeprecated

using Markdown
import Base.show_unquoted,Base.remove_linenums!


"""
    @mark_deprecated old msg 
Mark method `old` as deprecated. 
Print given `msg` on method call and prepend `msg` to the method's documentation.
        MACRO IS UNFINISHED AND NOT WORKING!!!!!
"""
macro mark_deprecated(old,msg="Default deprecation warning.",new=:())
    Meta = Expr(:Meta,Symbol)
        # if called with only function symbol,e.g. f,declare method f(args...)
        Expr(:toplevel,:(
                @doc(  # This Syntax is riddiculous,right?!?
                    "$(Markdown.MD($"`$old` is deprecated,@doc($(esc(old)))))",function $(esc(old))(args...)
                    $Meta
                    warn_deprecated($"`$old` is deprecated,Core.Typeof($(esc(old))).name.mt.name)
                    $(esc(new))(args...)
                    end
                )
            )
        )
    elseif isa(old,Expr) && (old.head === :call || old.head === :where)
        # if called with a "call",e.g. f(a::Int),or with where,e.g. f(a:A) where A <: Int,# try to redeclare that method
        error("not implemented yet.")
        remove_linenums!(new)
        # if old.head is a :where,Expr) && callexpr.args[1].head === :curly
                oldsym = callexpr.args[1].args[1]::Symbol
            else
                error("invalid usage of @mark_deprecated")
            end
        else
            error("invalid usage of @mark_deprecated")
        end
        Expr(:toplevel,:($(esc(old)) = begin
            $Meta
            warn_deprecated($"`$oldcall` is deprecated,Core.Typeof($(esc(oldsym))).name.mt.name)
            $(esc(old)) # Todo: this replaces the deprecated function!!!
        end))
    else
        error("invalid usage of @mark_deprecated")
    end
end


function warn_deprecated(msg,funcsym)
    @warn """
            Warning! Using deprecated symbol $funcsym.
            $msg
            """
end

end # Module MarkDeprecated

用于测试:

module Testing

import ..MarkDeprecated  # (if in the same file)

a(x) = "Old behavior"
MarkDeprecated.@mark_deprecated a "Message" print

a("New behavior?")

end

问题

到目前为止,我没有做我想要做的两件事中的任何一个

  1. 我如何处理调用者未导入Markdown(用于连接文档字符串)的情况? (编辑:显然这不是问题?出于某种原因,尽管Markdown模块中未导入模块Testing,但修改似乎仍然有效。我不完全理解为什么。很难做到跟随执行宏生成代码的每个部分的位置...)
  2. 实际上如何避免替换该功能?从内部调用它会创建一个无限循环。我基本上需要一个Python风格的装饰器?也许这样做的方法是只允许将@mark_deprecated添加到实际的函数定义中? (这样的宏实际上就是我期望在标准库中找到的,并且在我掉进这个兔子洞之前就使用了)
  3. 在我的示例中,宏(对于@deprecate也是如此)不会影响方法a(x),因为它仅创建带有签名a(args...)方法,该方法的优先级较低参数调用,仅在函数符号上调用宏时。尽管对我而言并不明显,但这似乎是@deprecate的理想行为。但是,是否可以将宏认应用到裸函数符号以弃用 all 方法

解决方法

我认为您想要实现的目标与Base.@deprecate的目标不同。如果我理解正确:

  • 您不希望宏为不推荐使用的方法创建定义;您想注释一个手写定义
  • 您要修改文档字符串,@deprecate不需要

由于您是作为学习元编程的练习来做的,也许您可​​以尝试逐步编写自己的宏,而不是了解Base.@deprecate的工作原理并尝试对其进行调整。

关于您的具体问题:

1。呼叫者未导入Markdown时该如何处理?

也许下面的示例有助于解释事物的工作原理:

module MyModule

# Markdown.MD,Markdown.Paragraph and msg are only available from this module
import Markdown
msg(name) = "Hello $name"

macro greet(name)
    quote
        # function names (e.g. Markdown.MD or msg) are interpolated
        # => evaluated at macro expansion time in the scope of the macro itself
        # => refer to functions available from within the module
        $(Markdown.MD)($(Markdown.Paragraph)($msg($name)))

        # (But these functions are not called at macro expansion time)
    end
end
end

特别查看msg如何正确引用Main.MyModule.msg,这是您必须从“外部”上下文中调用它的方式:

julia> @macroexpand MyModule.@greet "John"
quote
    #= REPL[8]:8 =#
    (Markdown.MD)((Markdown.Paragraph)((Main.MyModule.msg)("John")))
end

julia> MyModule.@greet "John"
  Hello John

2。也许这样做的方法是只允许在实际函数定义中添加@mark_deprecated?

是的,那就是我要做的。

3。是否可以将宏默认应用到裸函数符号以弃用所有方法?

我认为从技术上讲,可以弃用给定函数的所有方法……或者至少在弃用代码运行时存在的所有方法。但是,随后将要定义的方法呢​​? 我个人不会那样做,只标记方法定义。



也许这样的东西可能是存根,它可以用作更复杂的宏的起点,精确地执行您想要的操作:

module MarkDeprecate
using Markdown
using MacroTools

function mark_docstring(docstring,message)
    push!(docstring,Markdown.Paragraph("Warning: this method is deprecated! $message"))
    docstring
end

function warn_if_necessary(message)
    @warn "This method is deprecated! $message"
end

macro mark_deprecate(msg,expr)
    fundef = splitdef(expr)
    prototype = :($(fundef[:name])($(fundef[:args]...);
                                   $(fundef[:kwargs]...)) where {$(fundef[:whereparams]...)})

    fundef[:body] = quote
        $warn_if_necessary($msg)
        $(fundef[:body])
    end

    quote
        Base.@__doc__ $(esc(MacroTools.combinedef(fundef)))
        Base.@doc $mark_docstring(@doc($prototype),$msg) $prototype
    end
end
end
julia> """
           bar(x::Number)
       
       some help
       """
       MarkDeprecate.@mark_deprecate "Use foo instead" function bar(x::Number)
           42
       end
bar

julia> """
           bar(s::String)
       
       This one is not deprecated
       """
       bar(s::String) = "not deprecated"
bar

julia> methods(bar)
# 2 methods for generic function "bar":
[1] bar(s::String) in Main at REPL[4]:6
[2] bar(x::Number) in Main at REPL[1]:23

julia> @doc(bar)
  bar(x::Number)

  some help

  Warning: this method is deprecated! Use foo instead

  bar(s::String)

  This one is not deprecated

julia> bar("hello")
"not deprecated"

julia> bar(5)
┌ Warning: This method is deprecated! Use foo instead
└ @ Main.MarkDeprecate REPL[1]:12
42