Reputation: 855
It turns out that it is really hard to google the word comment.
Is is possible to represent "comment" expressions in quotations abstract syntax tree?
<@ //this gets ignored by the compiler and don't inject the quotation
@>
If not, can you suggest a workaround to represent the comments?
Upvotes: 1
Views: 325
Reputation: 243061
As Ganesh points out, the Expr
type has no way of representing comments - the F# quotations really represent just the AST of the expression, rather than full information about the source code (although you can get a file name & a location of a quoted expression).
To somehow embed comments in quotations, you'd need to come up with a way of embedding comments as valid F# code that means something - so you could e.g. define a dummy function comment
and do something like this:
let comment (s:string) = ()
let sample =
<@ comment "this is not ignored"
1 + ( comment "this is also not ignored"
4 ) @>
Then you could write an active pattern that looks for an expression of the form comment "..."; <expr>
and extract the string and the following <expr>
:
open Microsoft.FSharp.Quotations
let (|Comment|_|) = function
| Patterns.Sequential(DerivedPatterns.SpecificCall <@@ comment @@> (None, [], [Patterns.Value(comment, _)]), body) ->
Some(unbox<string> comment, body)
| _ -> None
Using the pattern, we can now write an (incomplete) pattern matching that succeeds when the top-level expression is some commented body
expression:
match sample with
| Comment(comment, body) ->
printfn "// %s\n%A" comment body
This is not a very nice way of doing it, but I guess it is as good as it can get if you want to embed some annotations in a hand-written quotation code.
Upvotes: 8
Reputation: 29100
The Expr
type that quotations return doesn't contain any way to represent a comment, so this is very unlikely to be possible.
Upvotes: 3