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

Add optional AST node type #1760

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

Add optional AST node type #1760

wants to merge 1 commit into from

Conversation

msujew
Copy link
Member

@msujew msujew commented Nov 26, 2024

The proposed OptionalAstNode<T> is a generic type that sets all properties, that could be potentially missing due to parser errors, to be optional. However, this excludes specificially:

  • Properties inherited from AstNode (mainly the $type property which is always set).
  • All boolean properties. Those will be set to false by the parser, even if the property wasn't parsed.
  • All array property. Those will be set to [] by the parser.

This change adjusts the arithmetics language validator to use that new type to ensure that all properties are properly checked for truthyness before they are accessed. Inspired by the discussion in #1758.

@msujew msujew added the ast AST structure related issue label Nov 26, 2024
@@ -35,6 +35,11 @@ export interface GenericAstNode extends AstNode {
[key: string]: unknown
}

export type OptionalAstNode<T extends AstNode> = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[P in keyof T]: P extends keyof AstNode ? T[P] : T[P] extends any[] | boolean ? T[P] : T[P] | undefined;
Copy link

@sorawee sorawee Nov 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

Would it make sense to make this recursive too? I believe a child node that we want to recur downward is either AstNode[] or AstNode | undefined or AstNode. Do I miss anything else?

Here's my attempt to take a stab at it. (This is the first time in my life that I do type-level programming actually! Apologies if anything is off)

export type OptionalAstNode<T extends AstNode> = {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [P in keyof T]: 
    P extends keyof AstNode ? 
      T[P] : 
      T[P] extends AstNode[] ? 
        OptionalAstNode<T[P][number]>[] : 
        T[P] extends any[] | boolean ? 
          T[P] : 
          T[P] extends AstNode | undefined ? 
            OptionalAstNode<Extract<T[P], AstNode>> | undefined :  
            (T[P] extends AstNode ? OptionalAstNode<T[P]> : T[P]) | undefined;
};

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

Successfully merging this pull request may close these issues.

2 participants