Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you generate F# code using its AST?

I would like to generate F# code for a .fs file using the abstract syntax tree. I am able to generate a .cs file using the Roslyn API. Here is an example riak.cs file that the unit tests generate based on the riak.proto. I would like to do the same thing in F#. I do not want to create a type provider yet. Does anyone have any examples using FSharp.Compiler.Service, possible with Fantomas?

like image 874
Cameron Taggart Avatar asked Jul 14 '14 16:07

Cameron Taggart


2 Answers

I totally agree with Tomas' answer. You need the latter half of Fantomas pipeline. Here is some relevant information.

  • FSharp.Compiler.Service's AST module consists of relevant ASTs and other utility functions for creating AST nodes, which might be helpful for you.

  • In Fantomas project, there is formatAST function that takes an AST as an input and output a source code string.

like image 112
pad Avatar answered Oct 24 '22 12:10

pad


Fantomas is certainly the right thing to look at here. If you want to generate F# source code, you basically need two things:

  1. Build the AST that represents the source code you want to build. To do that, you need to use the untyped AST from the F# compiler service. The untyped syntax tree page documents how you can process it, but it should be a good starting point for learning about it. The AST of expressions is defined by the SynExpr type.

  2. Once you build the AST, you need to format it. The F# compiler does not include a pretty printer, but this is exactly what Fantomas does in the CodePrinter file, so you should be able to copy this & pass your AST to the formatting implemented there. I think Visual F# PowerTools might actually have a newer version of Fantomas, so check that out first.

This answer is all using untyped AST, which is probably a good fit for working with syntax of the language. There is also typed AST (created after type inference finishes), but that's hard to use and not a good fit here.

like image 40
Tomas Petricek Avatar answered Oct 24 '22 11:10

Tomas Petricek