从同一模块检索注释 [英] Retrieving annotations from the same module
问题描述
假设我定义了自己的注释类型:
Suppose I define my own annotation type:
{-# LANGUAGE DeriveDataTypeable #-}
module Def where
import Data.Data
data MyAnn = MyAnn Int deriving (Show, Typeable, Data)
和一些模板 Haskell 函数来访问它:
and some Template Haskell function to access it:
module TH where
import Def
import Language.Haskell.TH.Syntax
myAnn :: Name -> Q Exp
myAnn name = do
[MyAnn x] <- reifyAnnotations (AnnLookupName name)
lift x
我现在想像这样使用它:
I would now like to use it like this:
{-# LANGUAGE TemplateHaskell #-}
module Client where
import Def
import TH
x :: ()
x = ()
{-# ANN x (MyAnn 42) #-}
y :: Int
y = $(myAnn 'x)
但是这失败了,因为y
定义中的myAnn
调用从reifyAnnotations
获取了一个空列表.
But this fails because the myAnn
invocation in the definition of y
gets an empty list from reifyAnnotations
.
如果我像这样拆分Client
,它会起作用:
It works if I split Client
like this:
module Client1 where
import Def
x :: ()
x = ()
{-# ANN x (MyAnn 42) #-}
{-# LANGUAGE TemplateHaskell #-}
module Client2 where
import Client1
import TH
y :: Int
y = $(myAnn 'x)
有没有办法让类似整体的 Client
模块工作?
Is there a way to get something like the monolithic Client
module to work?
推荐答案
根据 文档:
相应地,reify
看到的类型环境包括所有顶级声明,直到紧接在前面的声明组的末尾,但仅此而已.
Accordingly, the type environment seen by
reify
includes all the top-level declarations up to the end of the immediately preceding declaration group, but no more.
解决您问题的有效方法是通过包含一个空的顶级声明拼接来强制开始一个单独的声明组,即只是
An effective workaround for your problem is to force the start of a separate declaration group by including an empty top-level declaration splice, i.e. just
$(return [])
这篇关于从同一模块检索注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!