蓝色天空.知识 · 实践 · 创造
我的收藏
Julia 教程目录 24章
Julia / LEARN BY DOING

Julia 元编程

用抽象语法树、引用、宏展开和自定义类型上的方法生成理解代码数据。

学完这一章,你能够

  • 用抽象语法树、引用、宏展开和自定义类型上的方法生成理解代码数据。

从文本到语法树

Julia 可以把源码表示为 Expr 等语法对象。Meta.parse 解析表达式但不会运行它,解析结果也可能是字面值或 Symbol。Expr.head 表示构造类别,Expr.args 保存有序参数。Meta.show_sexpr 与 dump 可检查嵌套层次。

Symbol 表示名称本身,:(表达式) 表示未经执行的语法,quote…end 可保存代码块。引用里的 $ 可插入调用前已取得的字面值或另一棵表达式树。未引用的代码使用该插值形式会报错。

求值、宏展开和卫生性

Core.eval(module, expr) 在给定模块的全局范围内求值,函数内的同名局部变量不会改变它的查找范围。本站仅执行固定、自编的语法对象。普通函数、闭包和高阶函数能表达时优先使用它们。

宏接收语法参数,在宏展开阶段返回替换后的语法。@macroexpand 可查看结果,@assert 的展开可利用原来的表达式。临时局部名通常由宏卫生机制重命名,esc 可让明确选定的语法在调用环境解释。

字面量宏与生成方法

自定义前缀字符串由对应的名字加 _str 的宏处理。Julia 自带的正则和字节字面量也使用这一机制。正则宏的真实实现还负责标志等行为,不能用最短的示意宏当作标准实现。

可以用 @eval 生成重复的定义。本站只给自编的 Reading 类型添加数个 Base 函数的方法,保持模块范围明确。已有类型或方法的扩展需注意归属和接口约定。

元编程实例:查看展开并核对调用方作用域

含完整源码 · 95 行
展开查看收起
julia

include(joinpath(@__DIR__, "observations.jl"))

text="7 + 11"
parsed=Meta.parse(text)
built=Expr(:call,:+,7,11)
nested=Meta.parse("(7+11)/3")
sexpr=sprint(Meta.show_sexpr,nested)
probe("meta_parse",text,(typeof(parsed),parsed.head,parsed.args,parsed==built,
      Meta.parse("7"),Meta.parse("station"),occursin("(:call, :+",sexpr)),
      (Expr,:call,Any[:+,7,11],true,7,:station,true))
station=73
probe("meta_symbol","symbol versus bound value",(:station,typeof(:station),station),(:station,Symbol,73))
quoted=:(x+y*3+7)
constructed=Expr(:call,:+,:x,Expr(:call,:*,:y,3),7)
block=quote
    x=7
    y=11
    x+y
end
probe("meta_quote","single expression and block",(quoted==constructed,quoted==Meta.parse("x+y*3+7"),
      block.head,length(filter(node->!(node isa LineNumberNode),block.args))), (true,true,:block,3))
module TeachingScope
    x=7
end
absent_binding=outcome(() -> Core.eval(TeachingScope,:(x+y)))
Core.eval(TeachingScope,:(y=11))
value=let x=99
    Core.eval(TeachingScope,:(x+y))
end
probe("meta_eval","owned AST in a fixed module",(absent_binding,value,Core.eval(TeachingScope,block)),("UndefVarError",18,18))
tree=:(2*cos(pi/3))
buffer=IOBuffer()
dump(buffer,tree)
inspection=String(take!(buffer))
probe("meta_dump","2*cos(pi/3)",(tree.head,tree.args[3].args[1],occursin("Symbol cos",inspection)),
      (:call,:cos,true))
increment=7
interpolated=:($increment + x)
tuple_ast=:((7,11))
membership=:(x in $tuple_ast)
probe("meta_interpolate","interpolated literal and nested tuple AST",
      (interpolated.args, membership.args[3].head,Core.eval(TeachingScope,membership),
       outcome(() -> Core.eval(TeachingScope,Expr(:$,:x)))),
      (Any[:+,7,:x],:tuple,true,"ErrorException"))

macro greeting()
    :("station ready")
end
macro label(value)
    :(string("station: ",$(esc(value))))
end
name="Harbor"
probe("meta_macros","no arguments and a caller binding",(@greeting(),@label(name)),
      ("station ready","station: Harbor"))
expanded=@macroexpand @label(name)
assertion=@macroexpand @assert 7==11
probe("meta_macroexpand","inspect own macro and @assert",
      (expanded.head,Core.eval(@__MODULE__,expanded),occursin("AssertionError",string(assertion)),
       outcome(() -> (@assert 7==11))),(:call,"station: Harbor",true,"AssertionError"))

macro add_offset(expression)
    quote
        scratch=3
        scratch+$(esc(expression))
    end
end
macro zero_count()
    esc(:(count=0))
end
function exercise_hygiene()
    scratch=7
    result=@add_offset scratch
    count=11
    @zero_count
    (scratch,result,count)
end
probe("meta_hygiene","caller scratch and explicit assignment",exercise_hygiene(),(7,10,0))

macro tag_str(s)
    uppercase(s)
end
probe("meta_literal","custom tag, regex literal, byte literal",
      (tag"harbor",occursin(r"^N-\d+$","N-7"),Int.(collect(b"N"))),("HARBOR",true,[78]))
struct Reading
    value::Float64
end
for operation in (:sin,:cos,:tan,:log,:exp)
    @eval Base.$operation(x::Reading)=Reading($operation(x.value))
end
r=Reading(.6)
probe("meta_generated","extend five Base methods on a local type",
      (sin(r).value≈sin(.6),cos(r).value≈cos(.6),tan(r).value≈tan(.6),
       log(r).value≈log(.6),exp(r).value≈exp(.6)),(true,true,true,true,true))
调用方 scratch 保留为 7,宏内部计算得 10,显式逃逸的赋值把调用方 count 改为 0。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本机练习工程

解压后按 README 运行。文件例程仅操作临时文件和本机 HTTP 测试数据。

下载本章实验包 (mbskycom202612a205.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Julia

课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a205.zip

下载课程关联工程包:Julia

课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202612a208.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

语法可以合法,但模块可能缺绑定,或求值阶段出现运行错误。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习