Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change the postprocess data parameter type on the NearleyRule interface #637

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

misdocumeno
Copy link

@misdocumeno misdocumeno commented May 26, 2023

the interface currently looks like this

interface NearleyRule {
    name: string
    symbols: NearleySymbol[]
    postprocess?: (d: any[], loc?: number, reject?: {}) => any
}

I suggest this small change

interface NearleyRule {
    name: string
    symbols: NearleySymbol[]
    postprocess?: (d: any, loc?: number, reject?: {}) => any
}

from d: any[] to d: any, so you can use a tuple to define the type of the parameter, which makes much more sense, instead of an array, since production rules match a specific sequence of tokens, in a particular order, for example, with a grammar like this:

ReturnStatement -> %RETURN Expression %SEMICOLON {% returnStatement %}

and a postprocessor like this:

interface ReturnStatement {
  type: 'ReturnStatement'
  expression: Expression
}

function returnStatement(data: [ReturnToken, Expression, Semicolon]): ReturnStatement {
  return {
    type: 'ReturnStatement',
    expression: data[1], // no errors
  }
}

that tuple is not assignable to any[], since the any[] array could be any length, less than 3, but that will never happen.
for it to be assignable to any[], the postprocessor should look like this:

function returnStatement(data: (ReturnToken | Expression | Semicolon)[]): ReturnStatement {
  return {
    type: 'ReturnStatement',
    expression: data[1], // error, data[1] could be any of those 3 types
  }
}

which adds the need for runtime type checking with type predicates or something.

this change wouldn't cause any compilation error on existing grammars because any[] is assignable to any, so any code assuming d is an array, will still work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant