从同一模块中检索注释

时间:2015-11-06 08:15:48

标签: haskell annotations template-haskell

假设我定义了自己的注释类型:

{-# LANGUAGE DeriveDataTypeable #-}
module Def where

import Data.Data

data MyAnn = MyAnn Int deriving (Show, Typeable, Data)

和一些模板Haskell函数来访问它:

module TH where

import Def
import Language.Haskell.TH.Syntax

myAnn :: Name -> Q Exp
myAnn name = do
    [MyAnn x] <- reifyAnnotations (AnnLookupName name)
    lift x

我现在想像这样使用它:

{-# LANGUAGE TemplateHaskell #-}
module Client where

import Def
import TH

x :: ()
x = ()
{-# ANN x (MyAnn 42) #-}

y :: Int
y = $(myAnn 'x)

但是这会失败,因为myAnn定义中的y调用会从reifyAnnotations获取一个空列表。

如果我像这样分割Client,那就有效:

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模块工作?

1 个答案:

答案 0 :(得分:0)

这似乎是根据the docs预期的行为:

  

因此,reify看到的类型环境包括直到前一个声明组末尾的所有顶级声明,但不包括。

您的问题的有效解决方法是 通过包含一个空的顶级声明拼接来强制单独声明组的开始,即只需

$(return [])