F#报价和代码注释表达式

时间:2014-01-17 10:14:49

标签: f# metaprogramming

事实证明,谷歌评论这个词真的很难。

是否可以在引号中表示“注释”表达式抽象语法树?

<@ //this gets ignored by the compiler and don't inject the quotation
@>

如果没有,您能建议一种解决方法来表示评论吗?

2 个答案:

答案 0 :(得分:8)

正如Ganesh指出的那样,Expr类型无法表示注释 - F#引用实际上只代表表达式的AST,而不是源代码的完整信息(尽管您可以获取文件名) &amp;引用表达式的位置。)

以某种方式将注释嵌入引号中,您需要提出一种将注释作为有效F#代码嵌入的方法 - 这意味着您可以使用定义一个虚函数comment,并执行以下操作:

let comment (s:string) = ()

let sample =
  <@ comment "this is not ignored"
     1 + ( comment "this is also not ignored"
           4 ) @> 

然后你可以编写一个活动模式来查找comment "..."; <expr>形式的表达式并提取字符串和以下<expr>

open Microsoft.FSharp.Quotations

let (|Comment|_|) = function
  | Patterns.Sequential(DerivedPatterns.SpecificCall <@@ comment @@> (None, [], [Patterns.Value(comment, _)]), body) ->
      Some(unbox<string> comment, body)
  | _ -> None

使用该模式,我们现在可以编写一个(不完整的)模式匹配,当顶级表达式是一些注释body表达式时,该模式匹配成功:

match sample with
| Comment(comment, body) -> 
    printfn "// %s\n%A" comment body

这不是一个非常好的方法,但我想如果你想在手写的引用代码中嵌入一些注释,那就好了。

答案 1 :(得分:3)

引用返回的Expr类型不包含任何表示注释的方式,因此这种可能性很小。

相关问题