9

How does one make a comment in Lex and Yacc?

So far I haven't tried Yacc, but in Lex I have tried /* comment */ and // comment, but neither of these compile. I am on a Mac, using the builtin Lex and Yacc compilers, (or maybe the X-Code ones, I don't know). What is the correct syntax for comments in Lex or Yacc, or preferably both?

jellies
  • 639
  • 1
  • 5
  • 17

2 Answers2

7

Any C comment is acceptable as a comment anywhere in a program in both Yacc and Lex, BUT:

  • When using Lex or Yacc whitespace is important, so /* comment */ written into your program touching the LHS of your text will NOT WORK!
    • to make it work, you must add a tab or space to the beginning of the line, to shove it to C code, and not Lex or Yacc code.
  • gcc is a nice compiler and loves you very much, so it accepts // comment comments, Lex and Yacc are not nice. these comments, while will work in a C program, will NOT WORK!
jellies
  • 639
  • 1
  • 5
  • 17
5

From info flex:

In the definitions and rules sections, any indented text or text enclosed in %{ and %} is copied verbatim to the output (with the %{}'s removed). The %{}'s must appear unindented on lines by themselves.

In this case the text concerned can be a comment in the target language.

In the definitions section (but not in the rules section), an unindented comment (i.e., a line beginning with /*) is also copied verbatim to the output up to the next */.

Any valid C comment is a comment in a code block.

A comment in yacc is /* ... */.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • The Lex comment syntax of `# comment` does not work. (the declaration section is the middle one right?) – jellies May 17 '16 at 03:31
  • 1
    The declarations section is the first one. The middle one is the rule section. In the rules section, any indented line (begins with space or tab) is C code copied to the lex.yy.c file, so any C comments are valid and copied and treated as comments by the C compiler – Chris Dodd May 17 '16 at 03:55
  • 1
    @ChrisDodd, ah! so `[TAB] /* comment */` and `[TAB] // comment` should work then. – jellies May 17 '16 at 19:08
  • 1
    @Stegosaurus: yes, though the latter will only work if your C compiler accepts C++-style comments, or you're using a C++ compiler. – Chris Dodd May 18 '16 at 00:01
  • Oops. I was a *flex* user and contributor in the 1980s, but it's been a long time, and the part I wrote about `#` seems to have been complete fantasy. Corrected. – user207421 May 18 '16 at 00:29
  • @EJP is it possible to merge my answer with yours? I think if we do, it would function as a very informative answer that covered all the points necessary. – jellies May 18 '16 at 04:14
  • @Stegosaurus Why? I don't see anything in your answer that isn't covered in mine more rigorously and with quotations and citations. – user207421 Feb 24 '20 at 05:49