0

I am searching for c grammar and found this link https://www.lysator.liu.se/c/ANSI-C-grammar-y.html#cast-expression the issue is there is grammar for c and lex code but i don't see any semantics like addition ,multiplication implemented i know that yacc is used for only syntax check but we can also write semantics in it where are the semantics implemented are they implemented in other tool.

I am trying to implement a small compiler where do i write semantics ,is it good to write them in yacc using functions.

Jeevansai Jinne
  • 147
  • 2
  • 4
  • 12

1 Answers1

2

That example grammar (which is for a very old version of C) does not contain any particular semantics. You could certainly add them; the semantic rules would depend on what sort of tool you were building.

Bison/yacc is certainly a possible tool to build a compiler with. Many people have done so. Whether you refactor the semantic code into reusable functions​ or just put code directly into each action is a design choice​ which is up to you; I think most of us would recommend some use of functions to avoid code repetition.

rici
  • 234,347
  • 28
  • 237
  • 341
  • can you link me to some new c grammar – Jeevansai Jinne Apr 18 '17 at 19:10
  • @jeevansai: there's one in the C standard, although it requires some work to put it into bison format. Building a full C compiler is probably too ambitious for a first compiler project. I suggest you write your own grammar for a simpler language. You will learn more that way than copying something complicated without understanding it. Of course, there are parts of the C grammar which might be helpful as a guide. – rici Apr 18 '17 at 19:16
  • how to i save variables in bison – Jeevansai Jinne Apr 18 '17 at 19:37
  • Use a symbol table. There is an example in the bison manual, or in any other reasonable compiler tutorial. Here a a list of possible resources, although if you are taking a course, you might well already have a textbook or other useful study guide: http://stackoverflow.com/questions/1669/learning-to-write-a-compiler – rici Apr 18 '17 at 19:49
  • Bison manual example: https://www.gnu.org/software/bison/manual/bison.html#Multi_002dfunction-Calc – rici Apr 18 '17 at 19:51