metro-man
metro-man

Reputation: 1793

Parsing parameters and removing the last comma

Sorry for the bad title, not sure how else to write it. Anyhow, I'm using ANTLR to produce a parse tree. I'm attempting to parse function parameters, and it's sort of working but there are a few things I'd like to change, which I'm not exactly sure how to.

So here's my current setup:

function
    :   FUNCTION WORD LPAREN functionParams RPAREN ARROW WORD LBRACE RBRACE
    ;

functionParams
    :   (AMP WORD COMMA)*
    ;

// these could be wrong, I wrote these in by hand
AMP: '&';
WORD: [a-zA-Z_]+;
COMMA: ',';
LPAREN: '(';
RPAREN: ')';

Now this is great, it works. But when I input say

fn test(&x, &y, &z) -> int { }

It gives me an error, and an outcome I would prefer to change. The error being that it expects a comma after every parameter, so &z would become &z, which is not what I want.

Secondly, the tree it produces (gui) is like this:

wow

However, I would like the function parameters to be parsed to the tree like so (remove the commas for easier interpretation, and give each parameter it's own node).

    PARAMS
   /      \
&x          &y

Upvotes: 1

Views: 1401

Answers (1)

GRosenberg
GRosenberg

Reputation: 5991

Regarding your first question, change

functionParams
    :   (AMP WORD COMMA)*
    ;

to

functionParams
    :   ( param ( COMMA param )* )?
    ;

param
    :   AMP WORD
    ;

Regarding your second question, you do not indicate the version of Antlr you are using. If it is Antlr V4, the parser can only produce a parse tree, not an AST. As a practical matter, working with a parse tree is little different than with an AST - just walk it and extract information from the nodes of interest. With a little planning, you can define grammar rules that well isolate useful information into parse tree nodes of their own, such as the param rule above. You are, of course, free to walk the parse tree and generate an AST of your own design.

If you are using Antlr V3, the parser will produce an AST directly. The parser grammar syntax also permits shaping of the AST, including skipping of nodes, in a fairly flexible manner. The advantages of V3 are not so great, however, to recommend it in general over Antlr V4.

Upvotes: 3

Related Questions