Search code examples
haskellcompiler-constructionabstract-syntax-treepretty-printcurly-braces

Create data with Curly Braces in Haskell


I am trying to create an AST and pretty print it. I am parsing parts of the C language. However, when I have to represent an empty statement, which is

{}

I am completely stuck, because I am not able to simply create a new Data which contains something like that. Or when it be the following

{{}}

which would be the equivalent of

SScope({})

Technically my question is, how I am able to pretty-print in Haskell the Curly braces? So when I receive

{}

I would like to pretty-print exactly the same, like

{}

that. And what I would do is something like this:

data Stmt = {}

like with other data elements, but I am not able to do this. Any advice for that?


Solution

  • You need to distinguish between the lexical components of your language (the curly braces etc) and the Haskell data types used to represent the syntactic constructs.

    The Haskell side should have something like

    data Stmt = 
        CompoundStmnt [Stmt]
        | ValueStmt Identifier Expression
        |  -- And so on for all the other types of statement you want.
    

    Then you define a parser which recognises curly brackets, and a pretty-printer which prints out the values surrounded by curly brackets.