lalrpop: Whitespace/SeperatedBy Problem

I am attempting to parse Lua statements, I run into a small but persistent issue though

use crate::structure::{
    ...
};
use std::str::FromStr;

grammar;

SeparatedBy<T, Sep>: Vec<T> = {
    <v:(<T> Sep)*> <e:T?> => match e {
        None => v,
        Some(e) => {
            let mut v = v;
            v.push(e);
            v
        }
    }
};

pub Program: AST<'input> = { <block:Block> => AST { root: block } };
pub Block: Block<'input> = { <stmts:Stmt*> => Block { statements: stmts } };

pub Stmt: StmtASTNode<'input> = {
   <local:"local"?> <variables:SeparatedBy<Identifier, ",">> "=" <init:SeparatedBy<Expr, ",">> => StmtASTNode::AssignmentStatement(
       AssignmentStatement::new(
           variables.iter().map(|i| Identifier::new(*i)).collect::<Vec<_>>(),
           init,
           local.is_some()
       )
    )
};



pub Expr: ExprASTNode<'input> = {
    ...
}

The issue here is simple, the match below needs some sort of “end bound”.

<local:"local"?> <variables:SeparatedBy<Identifier, ",">> "=" <init:SeparatedBy<Expr, ",">>

The problem I am running into though is that there is no required separator, so the below snippet of code is valid

local x = 4 local function y() end

How exactly do I solve this issue?

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 18 (9 by maintainers)

Most upvoted comments

@chanbengz I think you want to use repetition operators like + or * instead of referring recursively to SeparatedBy. Since this is a macro and not a normal rule, I believe will just be expanded indefinitely until the recursion limit?

For the record, here are the kind of macros I use to handle this:

// Repeat a rule zero times or more with a separator interspersed, such that the last
// separator is optional: for example, Delimiter<Term, ","> will both accept
// `1,2` and `1,2,`.
RepeatSep<Rule, Sep>: Vec<Rule> = <mut elems: (<Rule> Sep)*> <last: Rule?> => {
    elems.extend(last);
    elems
};

// Same as `RepeatSep`, but repeat the rule at least once (one or more), instead
// of zero or more.
RepeatSep1<Rule, Sep>: Vec<Rule> = <mut elems: (<Rule> Sep)*> <last: Rule> Sep? => {
    elems.push(last);
    elems
};

The issue here is simple, the match below needs some sort of “end bound”.

I have no idea what you mean by “end bound”. Could you elaborate on it?

Possibly a quick fix would be

SeparatedBy<T, Sep>: Vec<T> = {
-   <v:(<T> Sep)*> <e:T?> => match e {
+   <mut v:SeparatedBy<T, Sep>> <e:T?> => match e {
        None => v,
        Some(e) => {
-           let mut v = v;
            v.push(e);
            v
        }
-   }
+   },
+   <e:T> => vec![e],
};

which is to add a rule for single element, and turn * to +, based on my understanding.

BTW, please ask in Discussions next time for the use case problem because it’s not related to LALRPOP itself. Issues are intended for feature/bug/improvement…