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?
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.
Fantomas is certainly the right thing to look at here. If you want to generate F# source code, you basically need two things:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With