Search code examples
compiler-constructionbisonflex-lexer

flex and bison:how to add semantics action in my parser?


I am trying to make a small compiler for my language. I have already written lexer and parser using flex and bison but in parser i have not used any semantic actions since I don't know how to use it for type checking and so. I have read about semantic analyzer ,I just want to know what are the steps need to be followed for performing semantics analysis using parser. Do I need to create NODE,AST etc if yes then please suggest any example how to do it?


Solution

  • The basic bison parser just gives a boolean answer -- yes or no, does the input match the language described by the grammar. If you want to do anything more than that (for example, compiling the program described by the langauge somehow), you'll need to add semantic actions.

    Semantic actions in bison are very flexible -- they are arbitrary bits of code that can do anything you want. So you need to decide what you want to do in those actions to acheive whatever the goal of your program is.

    The general idea behind bison semantic actions is that the parser will run each action when the associated rule is reduced, so you can set up your actions to do things a response to rules being recognized as they are reduced. As such you can evaluate the 'meaning' of the reduced rule to produce some effect, or you can produce a fragment of AST in some convenient form for later processing. Rule actions can access the results of previously reduced rule actions in a bottom-up way. What you do depends on what you want.