[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Bison yyparse return array of values
From: |
Laura Morales |
Subject: |
Re: Bison yyparse return array of values |
Date: |
Sun, 2 Apr 2017 15:21:21 +0200 |
Thanks a lot Alex, this works great.
There is one more thing that I'd like to do. I'd like to have multiple parsers
available in the same codebase, such that I can invoke parser1() or parser2()
or parser-n(), and in turn get some data structure back depending on the parser
I called. Just as an example, let's say I want two parser: one that returns an
array of numbers (ignoring all other tokens), and another one that only returns
words (ignoring all other tokens). This soon gets messy with global variables.
I've read in the documentation about the "prefix" option that allows me to
replace the "yy" namespace with something else, but if I understand correctly
there's another better option available: pure/reentrant parsers. This I
suppose, would get rid of globals, although I don't fully understand how this
"pure/reentrant" option work.
My question thus is how can I include multiple parsers together (in the same
program) while avoiding globals and also avoiding to turn my code into
spaghetti code?
Thanks once more.
========================================================
Hi Laura,
I would start with a global linked list that is filled in the semantic
actions. Building on your example:
================
%{
#include <stdio.h>
#include <stdlib.h>
typedef struct elem {
char *val;
struct elem *next;
} elem_t;
elem_t *words = NULL;
void add_word(char *val) {
elem_t *word = (elem_t *)malloc(sizeof(elem_t));
if (word == NULL) {
fprintf (stderr, "%s", "malloc failed");
exit(1); }
word->val = val;
word->next = words;
words = word;
}
%}
%output "parser.c"
%defines "parser.h"
%union { char *str; }
%token <str> WORD
%start Input
%%
Input
: WORD { add_word(yylval.str);
printf("word: %s\n", yylval.str); }
| Input WORD { add_word(yylval.str);
printf("word: %s\n", yylval.str); }
;
%%
================
Yours, Alex