String input to flex lexer

Chcę utworzyć pętlę read-eval-print przy użyciu parsera flex/bison. Problem w tym, że generowany przez flex lexer chce wprowadzić plik typu * i chciałbym, aby był to znak*. Czy w ogóle można to zrobić?

Jedną z sugestii było utworzenie rury, podanie jej łańcucha i otwarcie deskryptora pliku i wysłanie do lexera. Jest to dość proste, ale wydaje się zawiłe i niezbyt niezależne od platformy. Jest lepszy sposób?

Author: lesmana, 2009-04-23

7 answers

Następujące procedury są dostępne do konfigurowania buforów wejściowych do skanowania łańcuchów w pamięci zamiast plików (tak jak robi to yy_create_buffer):

  • YY_BUFFER_STATE yy_scan_string(const char *str): skanuje łańcuch zakończony znakiem NUL '
  • YY_BUFFER_STATE yy_scan_bytes(const char *bytes, int len): skanuje bajty len (w tym ewentualnie NULs) zaczynając od bajtów lokalizacji

Zauważ, że obie te funkcje tworzą, zwracają odpowiedni uchwyt yy_buffer_state (który musisz usunąć za pomocą yy_delete_buffer (), gdy to zrobisz) , więc yylex () skanuje kopię string lub bajty. Takie zachowanie może być pożądane, ponieważ yylex () modyfikuje zawartość skanowanego bufora).

Jeśli chcesz uniknąć kopiowania (i yy_delete_buffer) za pomocą:

  • YY_BUFFER_STATE yy_scan_buffer(char *base, yy_size_t size)

Próbka główna:

int main() {
    yy_scan_buffer("a test string");
    yylex();
}
 52
Author: dfa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-04-23 08:10:37

Zobacz tę sekcję podręcznika Flex, aby dowiedzieć się, jak skanować bufory pamięci, takie jak łańcuchy znaków.

 17
Author: unwind,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-17 21:36:57

Flex może analizować char * używając dowolnej z trzech funkcji: yy_scan_string(), yy_scan_buffer() i yy_scan_bytes() (patrzDokumentacja ). Oto przykład pierwszego:

typedef struct yy_buffer_state * YY_BUFFER_STATE;
extern int yyparse();
extern YY_BUFFER_STATE yy_scan_string(char * str);
extern void yy_delete_buffer(YY_BUFFER_STATE buffer);

int main(){
    char string[] = "String to be parsed.";
    YY_BUFFER_STATE buffer = yy_scan_string(string);
    yyparse();
    yy_delete_buffer(buffer);
    return 0;
}

Równoważne instrukcje dla yy_scan_buffer() (które wymagają podwójnie zakończonego łańcucha null):

char string[] = "String to be parsed.\0";
YY_BUFFER_STATE buffer = yy_scan_buffer(string, sizeof(string));

Moja odpowiedź powtarza niektóre informacje dostarczone przez @dfa i @jlholland, ale żaden z ich kodu odpowiedzi nie wydawał się działać dla mnie.

 9
Author: sevko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-17 21:37:51

Oto co musiałem zrobić:

extern yy_buffer_state;
typedef yy_buffer_state *YY_BUFFER_STATE;
extern int yyparse();
extern YY_BUFFER_STATE yy_scan_buffer(char *, size_t);

int main(int argc, char** argv) {

  char tstr[] = "line i want to parse\n\0\0";
  // note yy_scan_buffer is is looking for a double null string
  yy_scan_buffer(tstr, sizeof(tstr));
  yy_parse();
  return 0;
}

Nie można wyeksploatować typedef, co ma sens, gdy się o tym pomyśli.

 8
Author: jlholland,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-15 21:05:15

Przyjęta odpowiedź jest nieprawidłowa. To spowoduje wycieki pamięci.

Wewnętrznie, yy_scan_string wywołuje yy_scan_bytes, które z kolei wywołuje yy_scan_buffer.

Yy_scan_bytes przydziela pamięć do kopii bufora wejściowego.

Yy_scan_buffer działa bezpośrednio na dostarczonym buforze.

W przypadku wszystkich trzech form, musisz wywołać yy_delete_buffer, aby uwolnić informacje o stanie bufora flex (yy_buffer_state).

Jednak z yy_scan_buffer unikasz wewnętrznego alokacja/kopiowanie / wolne od wewnętrznego bufora.

Prototyp dla yy_scan_buffer nie przyjmuje znaku const * i nie można oczekiwać, że zawartość pozostanie niezmieniona.

Jeśli przydzielono pamięć do przechowywania łańcucha, jesteś odpowiedzialny za zwolnienie go po wywołaniu yy_delete_buffer.

Nie zapomnij również, aby yywrap zwracał 1 (niezerowe)podczas parsowania tylko tego ciągu.

Poniżej znajduje się pełny przykład.

%%

<<EOF>> return 0;

.   return 1;

%%

int yywrap()
{
    return (1);
}

int main(int argc, const char* const argv[])
{
    FILE* fileHandle = fopen(argv[1], "rb");
    if (fileHandle == NULL) {
        perror("fopen");
        return (EXIT_FAILURE);
    }

    fseek(fileHandle, 0, SEEK_END);
    long fileSize = ftell(fileHandle);
    fseek(fileHandle, 0, SEEK_SET);

    // When using yy_scan_bytes, do not add 2 here ...
    char *string = malloc(fileSize + 2);

    fread(string, fileSize, sizeof(char), fileHandle);

    fclose(fileHandle);

    // Add the two NUL terminators, required by flex.
    // Omit this for yy_scan_bytes(), which allocates, copies and
    // apends these for us.   
    string[fileSize] = '\0';
    string[fileSize + 1] = '\0';

    // Our input file may contain NULs ('\0') so we MUST use
    // yy_scan_buffer() or yy_scan_bytes(). For a normal C (NUL-
    // terminated) string, we are better off using yy_scan_string() and
    // letting flex manage making a copy of it so the original may be a
    // const char (i.e., literal) string.
    YY_BUFFER_STATE buffer = yy_scan_buffer(string, fileSize + 2);

    // This is a flex source file, for yacc/bison call yyparse()
    // here instead ...
    int token;
    do {
        token = yylex(); // MAY modify the contents of the 'string'.
    } while (token != 0);

    // After flex is done, tell it to release the memory it allocated.    
    yy_delete_buffer(buffer);

    // And now we can release our (now dirty) buffer.
    free(string);

    return (EXIT_SUCCESS);
}
 3
Author: Tad Carlucci,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-28 00:19:05

W inny sposób, możesz ponownie zdefiniować funkcję YY_INPUT w pliku lex, a następnie ustawić ciąg znaków na wejście LEX. Jak poniżej:

#undef YY_INPUT
#define YY_INPUT(buf) (my_yyinput(buf))

char my_buf[20];

void set_lexbuf(char *org_str)
{  strcpy(my_buf, org_str);  }

void my_yyinput (char *buf)
{  strcpy(buf, my_buf);      } 

W Twoim głównym.c, przed skanowaniem musisz najpierw ustawić bufor Lexa:

set_lexbuf(your_string);
scanning...
 1
Author: Kingcesc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-16 05:28:13

Oto mały przykład użycia bison / flex jako parsera w kodzie cpp do parsowania ciągu znaków i zmiany wartości zgodnie z nim (kilka części kodu zostało usuniętych, więc mogą tam być nieistotne części.) parser.y:

%{
#include "parser.h"
#include "lex.h"
#include <math.h> 
#include <fstream>
#include <iostream> 
#include <string>
#include <vector>
using namespace std;
 int yyerror(yyscan_t scanner, string result, const char *s){  
    (void)scanner;
    std::cout << "yyerror : " << *s << " - " << s << std::endl;
    return 1;
  }
    %}

%code requires{
#define YY_TYPEDEF_YY_SCANNER_T 
typedef void * yyscan_t;
#define YYERROR_VERBOSE 0
#define YYMAXDEPTH 65536*1024 
#include <math.h> 
#include <fstream>
#include <iostream> 
#include <string>
#include <vector>
}
%output "parser.cpp"
%defines "parser.h"
%define api.pure full
%lex-param{ yyscan_t scanner }
%parse-param{ yyscan_t scanner } {std::string & result}

%union {
  std::string *  sval;
}

%token TOKEN_ID TOKEN_ERROR TOKEN_OB TOKEN_CB TOKEN_AND TOKEN_XOR TOKEN_OR TOKEN_NOT
%type <sval>  TOKEN_ID expression unary_expression binary_expression
%left BINARY_PRIO
%left UNARY_PRIO
%%

top:
expression {result = *$1;}
;
expression:
TOKEN_ID  {$$=$1; }
| TOKEN_OB expression TOKEN_CB  {$$=$2;}
| binary_expression  {$$=$1;}
| unary_expression  {$$=$1;}
;

unary_expression:
 TOKEN_NOT expression %prec UNARY_PRIO {result =  " (NOT " + *$2 + " ) " ; $$ = &result;}
;
binary_expression:
expression expression  %prec BINARY_PRIO {result = " ( " + *$1+ " AND " + *$2 + " ) "; $$ = &result;}
| expression TOKEN_AND expression %prec BINARY_PRIO {result = " ( " + *$1+ " AND " + *$3 + " ) "; $$ = &result;} 
| expression TOKEN_OR expression %prec BINARY_PRIO {result = " ( " + *$1 + " OR " + *$3 + " ) "; $$ = &result;} 
| expression TOKEN_XOR expression %prec BINARY_PRIO {result = " ( " + *$1 + " XOR " + *$3 + " ) "; $$ = &result;} 
;

%%

lexer.l : 

%{
#include <string>
#include "parser.h"

%}
%option outfile="lex.cpp" header-file="lex.h"
%option noyywrap never-interactive
%option reentrant
%option bison-bridge

%top{
/* This code goes at the "top" of the generated file. */
#include <stdint.h>
}

id        ([a-zA-Z][a-zA-Z0-9]*)+
white     [ \t\r]
newline   [\n]

%%
{id}                    {    
    yylval->sval = new std::string(yytext);
    return TOKEN_ID;
}
"(" {return TOKEN_OB;}
")" {return TOKEN_CB;}
"*" {return TOKEN_AND;}
"^" {return TOKEN_XOR;}
"+" {return TOKEN_OR;}
"!" {return TOKEN_NOT;}

{white};  // ignore white spaces
{newline};
. {
return TOKEN_ERROR;
}

%%

usage : 
void parse(std::string& function) {
  string result = "";
  yyscan_t scanner;
  yylex_init_extra(NULL, &scanner);
  YY_BUFFER_STATE state = yy_scan_string(function.c_str() , scanner);
  yyparse(scanner,result);
  yy_delete_buffer(state, scanner);
  yylex_destroy(scanner);
  function = " " + result + " ";  
}

makefile:
parser.h parser.cpp: parser.y
    @ /usr/local/bison/2.7.91/bin/bison -y -d parser.y


lex.h lex.cpp: lexer.l
    @ /usr/local/flex/2.5.39/bin/flex lexer.l

clean:
    - \rm -f *.o parser.h parser.cpp lex.h lex.cpp
 0
Author: Or Davidi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-24 10:47:47