How do you create F # code using your AST?

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

+6
source share
2 answers

I completely agree with Thomas's answer. You need the last half of the Fantomas pipeline. Here is some relevant information.

  • FSharp.Compiler.Service The AST module consists of the corresponding AST and other useful functions for creating AST nodes that may be useful to you.

  • In the Fantomas project, there is a formatAST function that takes an AST as an input and outputs a line of source code.

+5
source

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

  • Create an AST that represents the source code you want to create. To do this, you need to use untyped AST from the F # compiler service. an untyped syntax tree on the docs page, how you can handle it, but this should be a good starting point to learn this. AST expressions are determined by the type of SynExpr .

  • Once you create an AST, you need to format it. The F # compiler does not contain a nice printer, but this is exactly what Fantomas does in the CodePrinter file, so you should be able to copy it and transfer your AST to formatting implemented there. I think Visual F # PowerTools may have a newer version of Fantomas, so check this out first.

This answer uses untyped AST, which is probably suitable for working with language syntax. AST (created after type inference completion) is also printed, but it is difficult to use and is not suitable for this.

+8
source

Source: https://habr.com/ru/post/972184/


All Articles