F# and FParsec: a GLSL parser example

An example using FParsec and F# to parse a C-like language and generate the AST.

One of my side-projects is GLSL Minifier.

GLSL is the shading language of OpenGL, that is a language designed to run on the GPU, in order to control the graphics pipeline and create nice realtime graphical effects. GLSL is based on the C programming language (without pointers, without recursion, but with some extra keywords).

GLSL minifier transforms a GLSL code into an equivalent code that is as small as possible. This is is probably useless for you, unless you are into demoscene. It's a tool that will help you create awesome realtime animations in less than 4 kilobytes (like this or this), music included.

So, I wrote GLSL Minifier. I used F# of course, and also FParsec. I really enjoy FParsec, I believe it's more powerful than lex/yacc, even if it might look scary the first time (there are several new operators). In FParsec, you write very simple parsers, and then you mix them, you compose them to parse whatever you need. If you think in a functional way, I'm sure you'll love FParsec!

Here are the source files of my parser and the AST: glsl_parse.fs and glsl_ast.fs.

The code just parses the file given on the command line, generates the tree, and prints it. If you need to parse a C-like language, or any other computer language, you might find these files useful. The parser is not perfect (for instance, it doesn't handle the struct keyword, although it will be easy to add), but I think it's a good example you can play with and adapt to your needs.

Oh, by the way: GLSL Minifier was fully written under Windows, without portability in mind, but users reported me it works great on Linux and Mac. Thanks Mono!