Search code examples
parsingcompiler-constructionsemantics

why do we need attribute grammar in semantic analysis?


I am currently reading a book about compiler construction. In chapter 4 it spends a lot of space talking about attribute grammar, which confuses me a lot.

Why do we need it? and how is it used in production compiler?

enter image description here

It seems to me that attribute grammar is used to decorate a parse tree into abstract syntax tree. But why can't we build ASTs in the parsing phase?

For example, in OCaml, I can describe AST like this:

type ast =
  | Var of string
  | Num of int
  | If of test * then * else
  ...
  ...

To build an if node, I can simply do If (test, then, else)


Solution

  • If you wrote a lot of different compilers you might get tired of reproducing the same sorts of code over and over again. Things like attribute grammars reduce the amount of boilerplate coding by moving some obvious things into the grammar definition.

    You can ask the same question about systems like yacc--why not just write code to do the parsing? The answer is that after writing a few compilers you get tired of it and start wanting some higher-level help.

    Another advantage is that (if the system is implemented correctly), you avoid the opportunity to make errors in your boilerplate code.