Exchange memory between YACC, Lex, and C files

I have a YACC grammar (Bison), a Lex tokenizer (Flex), and a C program, among which I need to separate a struct (or indeed any variable). I am currently declaring the actual object in the grammar file and extern where I need it (i.e. my source C file), usually using a pointer to manipulate it. I have a common header file (and implementations) between a C file and a grammar file with functions useful for managing my data structure. It works, but it feels a little uncomfortable. Is there a better way to exchange memory between a grammar and a program?

+4
source share
2 answers

The header file for sharing the extern declaration between the source files it needs is the best way to go, as a rule. The main alternative is to provide it with "functional access" - that is, the function "get value" and "set value" (or a set of functions). This is usually an excess. Make sure you include the title in the grammar (where you define the variable), as well as in the lexer and other code, so that inconsistencies are identified as soon as possible.

+4
source

If you want to stick with the standard (POSIX) lex / yacc, then your only option is to switch to global variables / functions. If you are fine using the Bison and Flex extensions, there are several ways to pass variables, mostly related to adding extra parameters to yyparse () and yylex ().

In Bison, this is done through% lex-param and% parse-param.

 %parse-param { struct somestruct *mystruct } %lex-param { struct somestruct *mystruct } 

There are two different mechanisms in Flex, depending on whether you need a reenter lexer or not. Assuming you are using the default option (no reuse), you need to override YY_DECL:

 %{ #define YY_DECL int yylex(struct somestruct *mystruct) %} 

In reentrant Flex lexer, additional arguments can be added through the scanner structure that Flex supports in order to maintain its state. You want to define YY_EXTRA_TYPE; additional data can be obtained through yyget / set_extra ().

+2
source

Source: https://habr.com/ru/post/1304048/


All Articles