How to implement "array type" grammar like typescript with pegjs?

71 views Asked by At

my problem is in the implementation of "array type" like typescript.

according to my grammar. In "array type" you can use "[]" after any type (eg string or int or even array again like int[][]).

this is simplified version of my grammar:

start = type

type = array / bool / string / int

string = "string"
int = "int"
bool = "bool"

// problem
array = t:type "[]" { return { kind: "array",type: t }}

the above code throw an syntax error:

Error: Maximum call stack size exceeded

1

There are 1 answers

2
MfyDev On

Your grammar type can call array, array can call type again, and so on. You need to create a new type rule that contains array as last case so that it won't loop:

start = type

primitive = bool / string / int
type = primitive / array

string = "string"
int = "int"
bool = "bool"

array = t:type "[]" { return { kind: "array",type: t }}