Search code examples
c++bisonflex-lexerbisonc++

Invalid character error with flex and bison


%{ 
#include <stdio.h>
#include <stdarg.h>
#include <iostream>
#include <ostream>
#include <string>

#ifndef TDM_PIN_MAP_TEST
#include <tdmPinMap.h>

namespace dc {
  class tdmPinMap; 
}
#endif
#undef YYLMAX
#define YYLMAX 100000
extern int lineno;
extern "C" int yywrap();
#ifndef TDM_PIN_MAP_TEST
int yyerror(dc::tdmPinMap &pm,std::string msg);
#else
int yyerror(std::string msg);
#endif
extern "C" char yytext[];
extern "C" int yylex();
%}

#ifndef TDM_PIN_MAP_TEST
%parse-param {dc::tdmPinMap &pm}
#endif

%union
{
   int val;
   char *str;
}

%token EQUALS
%token COMMA
%token SEMICOLON
%token PACKAGE
%token PIN
%token PORT
%token <str> ALPHANUMERIC
%type <str> port_name
%type <str> pin_name
%type <str> package_name

%%
             ;
pin_name         : ALPHANUMERIC
             {
               $$ = $1;
             }
             ;
%%

#ifndef TDM_PIN_MAP_TEST
int yyerror(dc::tdmPinMap &pm,std::string msg)
#else
int yyerror(std::string msg)
#endif
{
  return 1;
}

My Question:

I'm getting invalid character error with below code.

#ifndef TDM_PIN_MAP_TEST
%parse-param {dc::tdmPinMap &pm}
#endif

Here I want to define parse-param only if TDM_PIN_MAP_TEST macro is not defined, but I get below error.

bison -d -v -d  pinMap.ypp
pinMap.ypp:28.1: invalid character: `#'
pinMap.ypp:28.2-7: syntax error, unexpected identifier
make: *** [pinmap_yacc.cpp] Error 1

Line number 28 is referring to the code I have pointed out above.

Any pointer to resolve the above error is appreciated.


Solution

  • Bison does not provide any mechanism for conditional inclusion of directives or rules. Lines resembling C preprocessor directives (such as #ifndef) outside of a C code block are going to be flagged as syntax errors.

    If you want to use the same bison source file for two different applicatiobs, you'll have to use some external macro preprocessor.

    I'd recommend avoiding the use of cpp because it doesn't kniw anything about bison syntax, and will likely make many undesired changes to the bison grammar file, including expanding preprocessor directives in code blocks and unexpected macro substitutions in bison rules.

    Your desired conditional inclusion looks pretty simple, so you could probably do it with a shell script. Or you could use m4, which must be present since bison relies on it.