2014-09-21

Generating F# code using its AST

A couple of months ago, I asked "How do you generate F# code using its AST?". Tomas Petricek and Anh-Dung Phan confirmed that I should be able to use the F# Compiler Service and Fantomas to construct and print the source code. I spent time today finishing this up. I am able to:
  • load, reformat, and print source
  • load and print AST details
  • create the AST from scratch and print the source
I'm using the untyped abstract syntax tree (AST). See ast.fs for details or the FCS documentation. The syntax tree is a tree of a bunch of tupples. When analyzing and constructing the tree, I find working with records to be easier. To allow working with records, I created a helper module AstRcd.fs for converting to and from records.

load, reformat, and print source

This simply loads a Hello.fs file and then Fantomas formats it.

load and print AST details

This isn't robust code. I wrote this code only to figure out what I needed to generate. It prints the basic names in the Hello.fs file.

create the AST from scratch and print the source

Here I am able to generate the F# source code from scratch that matches the Hello.Reformatted.fs above. I use records a lot. The code could be simplified with default records to make very readable code generation.