simc-ast-builder
Version:
Parser and AST generator for SimulationCraft files
94 lines • 3.29 kB
JavaScript
"use strict";
/**
* Template for creating ExpressionNode instances
* Provides a way to define reusable node structures
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NodeTemplate = void 0;
/**
* Template for creating ExpressionNode instances
*/
class NodeTemplate {
/**
* Create a new NodeTemplate
* @param type Type of nodes created from this template
* @param options Options for the template
*/
constructor(type, options = {}) {
this.type = type;
this.baseProperties = options.baseProperties || {};
this.validator = options.validator;
}
/**
* Apply the template with values to create a node
* @param values Values to override base properties
* @returns A new ExpressionNode based on this template
* @throws Error if the node is invalid
*/
apply(values = {}) {
const node = Object.assign(Object.assign({ expressionType: "neutral", kind: "expression", nodeType: this.type }, this.baseProperties), values);
// Validate the node
if (this.validator && !this.validator(node)) {
throw new Error(`Invalid node of type ${this.type}`);
}
return node;
}
/**
* Validate a node against this template
* @param node Node to validate
* @returns True if the node is valid for this template
*/
validate(node) {
if (node.nodeType !== this.type) {
return false;
}
if (this.validator) {
return this.validator(node);
}
return true;
}
/**
* Create a new template with an additional validator
* @param additionalValidator Additional validator function
* @returns A new NodeTemplate with both validators
*/
withAdditionalValidator(additionalValidator) {
// Create a new validator that combines the existing validator (if any) with the additional one
const combinedValidator = (node) => {
// If there's no existing validator, just use the additional one
if (!this.validator) {
return additionalValidator(node);
}
// Otherwise, both validators must pass
return this.validator(node) && additionalValidator(node);
};
return this.withValidator(combinedValidator);
}
/**
* Create a new template with additional base properties
* @param properties Additional base properties
* @returns A new NodeTemplate with the combined base properties
*/
withBaseProperties(properties) {
const options = {
baseProperties: Object.assign(Object.assign({}, this.baseProperties), properties),
};
if (this.validator) {
options.validator = this.validator;
}
return new NodeTemplate(this.type, options);
}
/**
* Create a new template with a different validator
* @param validator New validator function
* @returns A new NodeTemplate with the new validator
*/
withValidator(validator) {
return new NodeTemplate(this.type, {
baseProperties: this.baseProperties,
validator,
});
}
}
exports.NodeTemplate = NodeTemplate;
//# sourceMappingURL=NodeTemplate.js.map