Nick Veys
Nick Veys

Reputation: 23939

Parsing var-args style commands with Bison

I'm fairly new to Flex/Bison and I'm trying to parse a string in the format:

COMMAND ARG1, ARG2, ARGn (, ARGn+1, ARGn+2 ...);

such that args 1, 2 and n are required, but n+1, n+2, ... are optional without limit.

How would I do this in Flex/Bison?

When I define my grammar as:

args:
  ARG
  |
  ARG COMMA args
;

var_command:
  COMMAND ARG COMMA ARG COMMA args SEMICOLON
  {
    printf("arg1: %s, arg2: %s\n", $2, $4);
  }

I can only (as above) reference the first 2 arguments, how do I reference what is being matched in the args: definition?

I've tested the grammar and I can throw any number of arguments at it, it is matching correctly, it's simply getting a handle on that data that escapes me.

Upvotes: 0

Views: 255

Answers (1)

Ise Wisteria
Ise Wisteria

Reputation: 11669

In this case, probably the list of ARGs needs to be created explicitly by the programmer.
For example(fictitious code):

%union { args_data *ad; }
%type <ad> args

%%

args:
  ARG
  {
    args_data *ad = alloc_args_data();
    append_arg(ad, $1);
    $$ = ad;
  }
  |
  args COMMA ARG
  {
    append_arg($1, $3);
    $$ = $1;
  }
;

Upvotes: 2

Related Questions