【问题标题】:How to get the declaration of a function using `reify`?如何使用`reify`获取函数的声明?
【发布时间】:2013-12-05 17:57:29
【问题描述】:

函数reify 允许我查找有关给定名称的信息。对于函数,返回值为VarI

data Info = ... |  VarI Name Type (Maybe Dec) Fixity  | ...

在这里我可以检查函数的类型,并且我还想检查它的声明。但是,在VarI 的第三个参数中,我总是看到Nothing。有没有办法获取函数的声明?

【问题讨论】:

标签: haskell template-haskell reify


【解决方案1】:

来自template haskell docs on the VarI Info contructor

“值”变量(与类型变量相反,请参阅TyVarI)。 Maybe Dec 字段包含 Just 定义变量的声明 - 包括声明的 RHS - 或 Nothing,在 RHS 对编译器不可用的情况下。目前这个值是alwaysNothing:由于兴趣不足,还没有实现返回RHS。

查看ghc source mirror on githubstring VarI only appears twice,以及在实现reifyThing 函数的compiler/typecheck/TcSplice.lhs 中:

reifyThing :: TcTyThing -> TcM TH.Info
-- The only reason this is monadic is for error reporting,
-- which in turn is mainly for the case when TH can't express
-- some random GHC extension

reifyThing (AGlobal (AnId id))
  = do  { ty <- reifyType (idType id)
        ; fix <- reifyFixity (idName id)
        ; let v = reifyName id
        ; case idDetails id of
            ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls) fix)
            _             -> return (TH.VarI     v ty Nothing fix)
    }

reifyThing (AGlobal (ATyCon tc))   = reifyTyCon tc
reifyThing (AGlobal (ADataCon dc))
  = do  { let name = dataConName dc
        ; ty <- reifyType (idType (dataConWrapId dc))
        ; fix <- reifyFixity name
        ; return (TH.DataConI (reifyName name) ty
                              (reifyName (dataConOrigTyCon dc)) fix)
        }

reifyThing (ATcId {tct_id = id})
  = do  { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even
                                        -- though it may be incomplete
        ; ty2 <- reifyType ty1
        ; fix <- reifyFixity (idName id)
        ; return (TH.VarI (reifyName id) ty2 Nothing fix) }

reifyThing (ATyVar tv tv1)
  = do { ty1 <- zonkTcTyVar tv1
       ; ty2 <- reifyType ty1
       ; return (TH.TyVarI (reifyName tv) ty2) }

reifyThing thing = pprPanic "reifyThing" (pprTcTyThingCategory thing)

就像模板 haskell 文档所说,用于该字段的值始终是 Nothing

深入挖掘,this code was added in 2003,看起来像是对 reify 系统的重写。因此,它似乎没有兴趣让它工作,因为该字段一直具有价值 Nothing 已经有 10 多年了。所以我猜你是否想要这个功能,你必须自己实现它(或者向 ghc 开发邮件列表提出一个好的用例,鼓励其他人这样做)。

【讨论】:

    猜你喜欢
    • 2020-03-21
    • 2020-08-11
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多