langium icon indicating copy to clipboard operation
langium copied to clipboard

Use common prototype for ast nodes

Open msujew opened this issue 4 years ago • 1 comments

Currently, instances of the AstNode interface use the Object prototype. In order to operate on these nodes, we currently use exported functions from files like ast-util.ts calculate additional information from the node like the document it belongs to. A call to them looks like this: getDocument(astNode).

I would propose to create a generic createAstNode method that automatically assigns a special AstNodePrototype prototype. This prototype would contain implementations for getDocument, streamContents etc. That way, we could use astNode.streamContents() instead.

Pros:

  • Fewer imports for the user
  • More obvious API surface for AstNodes.

Cons:

  • Makes everything more object oriented
  • Possible name conflicts, which could be resolved with our usual approach of prefixing with $

msujew avatar Aug 19 '21 12:08 msujew

The good thing about getDocument(astNode) is that it's very clear and no magic involved. Using prototypes would increase the API surface of the AST, so it would no longer be possible to create AST nodes with simple objects (this might become relevant if we go towards serialization at some point), but would require factory functions instead.

If in doubt, I'm for the variant that's slightly more verbose, but simpler.

spoenemann avatar Aug 23 '21 05:08 spoenemann

Closing because we won't change this API after version 1.0 anymore.

spoenemann avatar Dec 14 '22 14:12 spoenemann