No Newline at End of File

Programming, for all ages and all languages.
Post Reply
User avatar
AJ
Member
Member
Posts: 2646
Joined: Sun Oct 22, 2006 7:01 am
Location: Devon, UK
Contact:

No Newline at End of File

Post by AJ »

Hi,

Just out of interest, does anyone know the reason for the warning above when comiling with gcc? Why would the compiler warn that the last thing in the file has to be a newline - I'm sure there must be some good reason for this!

I'm normally compiling with Solar's huge list of -W flags found in his Makefile tutorial and this warning is the only one that I find irritating (particularly as I use -Werror) - albeit easily solved :)

Cheers,
Adam
User avatar
JamesM
Member
Member
Posts: 2935
Joined: Tue Jul 10, 2007 5:27 am
Location: York, United Kingdom
Contact:

Post by JamesM »

Because the grammar definition will be something like:

Code: Select all

complete_file: NEWLINE
  | declaration complete_file
  | definition complete_file
  ;

declaration: TYPE_SPECIFIER STRING 
  | TYPE_SPECIFIER STRING EQUALS STRING
  ;

blah blah blah...
Notice that the top rule isn't complete until a NEWLINE has been seen after all definitions/declarations have been parsed. So if you don't end with a newline, all input will have been used up and still the rule complete_file will not have fired! Special code would be nessecary to (possibly) add a newline on to the end of the input stream so that rule fires and the parser exits.

You may ask "Why not add something like this into the lexer?"

Code: Select all

<<EOF>>  {yylval="\n";return NEWLINE;}
To answer that: I don't know.
Last edited by JamesM on Mon Jan 14, 2008 6:29 am, edited 1 time in total.
Tyler
Member
Member
Posts: 514
Joined: Tue Nov 07, 2006 7:37 am
Location: York, England

Post by Tyler »

I'm not sure about the reasn the warning was added. But it is useful, for example, if you include a file without a new line at the end, and the new line after the include is eaten by the preprocessor to end the include, then the new file will have the next line appended to the end of the last line of the include file. Of course, i'm sure there are no compilers that fall into this trap.
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Post by Solar »

The reason is quite simple: It's required by the language standard that a non-empty source file shall end with an unescaped newline character. If GCC wouldn't spit a warning on this, it wouldn't be "standard compliant" in that regard.
Every good solution is obvious once you've found it.
User avatar
AJ
Member
Member
Posts: 2646
Joined: Sun Oct 22, 2006 7:01 am
Location: Devon, UK
Contact:

Post by AJ »

Thanks for the replies - perhaps I can be a little less annoyed by the warnings now I have some reasons for it!

Cheers,
Adam
Post Reply