langium
langium copied to clipboard
Use common prototype for ast nodes
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
$
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.
Closing because we won't change this API after version 1.0 anymore.