Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any built-in function for human-readable F# quotations?

Tags:

f#

quotations

When quoting

<@ 1 + 1 @>

I want "1 + 1"

instead of

"Call (None, Int32 op_Addition[Int32,Int32,Int32](Int32, Int32), [Value (1), Value (1)])"

like image 981
dotneter Avatar asked Sep 19 '09 17:09

dotneter


2 Answers

You'll have to write it yourself. See the F# quotations visualizer code as a guide for transforming the quotations abstract syntax tree.

like image 166
Jonathan Graehl Avatar answered Sep 30 '22 21:09

Jonathan Graehl


I have implemented a quotation decompiler as part of a larger open source project Unquote. It can decompile many simple F# quoted expressions as single-line non-light syntax strings (see the project's home page for a list of decompiler features). For example,

> decompile <@ (11 + 3) / 2 = String.length ("hello world".Substring(4, 5)) @>;;
val it : string =
  "(11 + 3) / 2 = String.length ("hello world".Substring(4, 5))"

@Kurt Schelfthout is correct about the many challenges faced when decompiling F# Quotations into human readable form. But from my work so far, I believe that it is possible to write a quotation decompiler which can generate correct F# code. Take match expressions and computation expressions for example, the Unquote decompiler can produce correct F# code in the following simple cases:

> decompile <@ match true with | true -> "hi" | _ -> "bye"  @>;;
val it : string =
  "let matchValue = true in if matchValue then "hi" else "bye""

> decompile <@ seq {yield 1; yield 2}  @>;;
val it : string =
  "seq (Seq.delay (fun unitVar -> Seq.append (Seq.singleton 1) (Seq.delay (fun unitVar -> Seq.singleton 2))))"

Infix and prefix operators are not too hard (as you can see in the first example), but source structure such as new lines and indentation is an interesting topic (though not terribly difficult, I think). However, single-line non-light syntax is sufficient for Unquote's requirements.

like image 37
Stephen Swensen Avatar answered Sep 30 '22 21:09

Stephen Swensen