Skip to content

Instantly share code, notes, and snippets.

@larryv
Created May 8, 2012 23:49
Show Gist options
  • Save larryv/2640482 to your computer and use it in GitHub Desktop.
Save larryv/2640482 to your computer and use it in GitHub Desktop.
Cool string definition
/*
* String constants (C syntax)
* Escape sequence \c is accepted for all characters c. Except for
* \n \t \b \f, the result is c.
*
*/
\" {
string_buf_ptr = string_buf;
BEGIN(STRING);
}
<STRING>{
"\b" STR_APPEND_CHAR('\b'); /* backspace */
"\f" STR_APPEND_CHAR('\f'); /* formfeed */
"\t" STR_APPEND_CHAR('\t'); /* tab */
"\n" STR_APPEND_CHAR('\n'); /* newline */
\\\n { /* escaped newline */
++curr_lineno;
STR_APPEND_CHAR('\n');
}
\\. STR_APPEND_CHAR(yytext[1]);
[^\\\n\"]+ {
if (string_buf_ptr + yyleng >
&string_buf[MAX_STR_CONST - 1]) {
BEGIN(INVALID_STRING);
RETURN_ERROR("String constant too long");
}
strncpy(string_buf_ptr, yytext, yyleng);
string_buf_ptr += yyleng;
}
\" {
BEGIN(INITIAL);
cool_yylval.symbol = stringtable.add_string(string_buf);
return STR_CONST;
}
\0 {
BEGIN(INVALID_STRING);
RETURN_ERROR("String contains null character");
}
\n {
++curr_lineno;
BEGIN(INITIAL);
RETURN_ERROR("Unterminated string constant");
}
<<EOF>> {
BEGIN(INITIAL); /* Prevent EOF loop */
RETURN_ERROR("EOF in string constant");
}
}
<INVALID_STRING>{
\\\n ++curr_lineno;
\\. ;
[^\\\n\"]+ ;
\" BEGIN(INITIAL);
\n {
++curr_lineno;
BEGIN(INITIAL);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment