typir
Version:
General purpose type checking library
78 lines • 3.27 kB
JavaScript
/******************************************************************************
* Copyright 2024 TypeFox GmbH
* This program and the accompanying materials are made available under the
* terms of the MIT License, which is available in the project root.
******************************************************************************/
import { isType } from '../graph/type-node.js';
import { TypeInitializer } from './type-initializer.js';
import { TypeReference } from './type-reference.js';
export class DefaultTypeResolver {
constructor(services) {
this.services = services;
}
tryToResolve(descriptor) {
if (isType(descriptor)) {
// TODO is there a way to explicitly enforce/ensure "as T"?
return descriptor;
}
else if (typeof descriptor === 'string') {
return this.services.infrastructure.Graph.getType(descriptor);
}
else if (descriptor instanceof TypeInitializer) {
return descriptor.getTypeInitial();
}
else if (descriptor instanceof TypeReference) {
return descriptor.getType();
}
else if (typeof descriptor === 'function') {
// execute the function and try to recursively resolve the returned result again
return this.tryToResolve(descriptor.call(descriptor));
}
else { // the descriptor is of type 'known' => do type inference on it
const result = this.services.Inference.inferType(descriptor);
// TODO failures must not be cached, otherwise a type will never be found in the future!!
if (isType(result)) {
return result;
}
else {
return undefined;
}
}
}
resolve(descriptor) {
if (isType(descriptor)) {
return descriptor;
}
else if (typeof descriptor === 'string') {
return this.handleError(this.services.infrastructure.Graph.getType(descriptor), `A type with identifier '${descriptor}' as TypeDescriptor does not exist in the type graph.`);
}
else if (descriptor instanceof TypeInitializer) {
return this.handleError(descriptor.getTypeFinal(), "This TypeInitializer don't provide a type.");
}
else if (descriptor instanceof TypeReference) {
return this.handleError(descriptor.getType(), 'This TypeReference has no resolved type.');
}
else if (typeof descriptor === 'function') {
// execute the function and try to recursively resolve the returned result again
return this.resolve(descriptor.call(descriptor));
}
else {
const result = this.services.Inference.inferType(descriptor);
if (isType(result)) {
return result;
}
else {
throw new Error(`For '${this.services.Printer.printLanguageNode(descriptor, false)}' as TypeDescriptor, no type can be inferred.`);
}
}
}
handleError(result, errorMessage) {
if (result) {
return result;
}
else {
throw new Error(errorMessage);
}
}
}
//# sourceMappingURL=type-descriptor.js.map