Skip to content

Instantly share code, notes, and snippets.

@spoenemann
Last active May 14, 2021 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spoenemann/7f8a7a5c491624e376537ccd606ad8a0 to your computer and use it in GitHub Desktop.
Save spoenemann/7f8a7a5c491624e376537ccd606ad8a0 to your computer and use it in GitHub Desktop.
Comparison of class-based vs. function-based DI service
export const ScopeComputationKey: BindingKey<ScopeComputation> = { id: 'ScopeComputation' };
export class ScopeComputation implements DIService {
private nameProvider: NameProvider;
initialize(services: ServiceHolder): void {
this.nameProvider = services.get(NameProvider);
}
computeScope(document: LangiumDocument): void {
const scopes = new Map();
document.precomputedScopes = scopes;
streamAllContents(document.parseResult.value).forEach(content => {
const { node } = content;
const container = node.$container;
if (container) {
const name = this.nameProvider(node);
if (name) {
const description = this.createDescription(node, name, document);
if (scopes.has(container)) {
scopes.get(container)?.push(description);
} else {
scopes.set(container, [description]);
}
}
}
});
}
protected createDescription(node: AstNode, name: string, document: LangiumDocument): AstNodeDescription {
return {
name,
type: node.$type,
documentUri: document.documentUri
};
}
}
export type ScopeComputation = (document: LangiumDocument) => void;
export const ScopeComputation: BindingKey<ScopeComputation> = { id: 'ScopeComputation' };
export const DefaultScopeComputation: Factory<ScopeComputation> = serviceHolder => {
const nameProvider = serviceHolder.get(NameProvider);
const createDescription = serviceHolder.get(createDescriptionKey);
return (document: LangiumDocument) => {
const scopes = new Map();
document.precomputedScopes = scopes;
streamAllContents(document.parseResult.value).forEach(content => {
const { node } = content;
const container = node.$container;
if (container) {
const name = nameProvider(node);
if (name) {
const description = createDescription(node, name, document);
if (scopes.has(container)) {
scopes.get(container)?.push(description);
} else {
scopes.set(container, [description]);
}
}
}
});
};
};
export const createDescriptionKey: BindingKey<typeof createDescription> = { id: 'createDescription', context: ScopeComputation };
export const createDescription = (node: AstNode, name: string, document: LangiumDocument): AstNodeDescription => {
return {
name,
type: node.$type,
documentUri: document.documentUri
};
};
export const DefaultScopeComputationModule: DIModule = container => {
container.bindToValue(createDescriptionKey, createDescription);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment