Cod*_*day 1 f# metaprogramming
事实证明,谷歌评论这个词真的很难.
是否可以在引号中表示"注释"表达式抽象语法树?
<@ //this gets ignored by the compiler and don't inject the quotation
@>
Run Code Online (Sandbox Code Playgroud)
如果没有,您能否建议一个解决方法来表示评论?
正如Ganesh指出的那样,Expr类型无法表示注释--F#引用实际上只代表表达式的AST,而不是源代码的完整信息(尽管您可以获取文件名和引用表达式的位置) .
为了以某种方式在引号中嵌入注释,您需要提出一种将注释作为有效F#代码嵌入的方法 - 这意味着您可以例如定义一个虚函数comment并执行以下操作:
let comment (s:string) = ()
let sample =
<@ comment "this is not ignored"
1 + ( comment "this is also not ignored"
4 ) @>
Run Code Online (Sandbox Code Playgroud)
然后你可以编写一个活动模式来查找表单的表达式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
Run Code Online (Sandbox Code Playgroud)
使用该模式,我们现在可以编写一个(不完整的)模式匹配,当顶级表达式是一些注释body表达式时,该模式匹配成功:
match sample with
| Comment(comment, body) ->
printfn "// %s\n%A" comment body
Run Code Online (Sandbox Code Playgroud)
这不是一个非常好的方法,但我想如果你想在手写的引用代码中嵌入一些注释,那就好了.