|
| 1 | +import { hasContainerOfType, ValidationAcceptor } from 'langium'; |
| 2 | +import { isSdsClass, SdsFunction } from '../../generated/ast.js'; |
| 3 | +import { SafeDsServices } from '../../safe-ds-module.js'; |
| 4 | +import { findFirstAnnotationCallOf, getParameters } from '../../helpers/nodeProperties.js'; |
| 5 | +import { pluralize } from '../../../helpers/stringUtils.js'; |
| 6 | + |
| 7 | +export const CODE_PYTHON_CALL_INVALID_TEMPLATE_EXPRESSION = 'python-call/invalid-template-expression'; |
| 8 | + |
| 9 | +export const pythonCallMustOnlyContainValidTemplateExpressions = (services: SafeDsServices) => { |
| 10 | + const builtinAnnotations = services.builtins.Annotations; |
| 11 | + |
| 12 | + return (node: SdsFunction, accept: ValidationAcceptor) => { |
| 13 | + const pythonCall = builtinAnnotations.getPythonCall(node); |
| 14 | + if (!pythonCall) { |
| 15 | + return; |
| 16 | + } |
| 17 | + |
| 18 | + // Get actual template expressions |
| 19 | + const match = pythonCall.matchAll(/\$[_a-zA-Z][_a-zA-Z0-9]*/gu); |
| 20 | + const actualTemplateExpressions = [...match].map((it) => it[0]); |
| 21 | + |
| 22 | + // Compute valid template expressions |
| 23 | + const validTemplateExpressions = new Set(getParameters(node).map((it) => `\$${it.name}`)); |
| 24 | + if (hasContainerOfType(node, isSdsClass)) { |
| 25 | + validTemplateExpressions.add('$this'); |
| 26 | + } |
| 27 | + |
| 28 | + // Compute invalid template expressions |
| 29 | + const invalidTemplateExpressions = actualTemplateExpressions.filter((it) => !validTemplateExpressions.has(it)); |
| 30 | + |
| 31 | + // Report invalid template expressions |
| 32 | + if (invalidTemplateExpressions.length > 0) { |
| 33 | + const kind = pluralize(invalidTemplateExpressions.length, 'template expression'); |
| 34 | + const invalidTemplateExpressionsString = invalidTemplateExpressions.map((it) => `'${it}'`).join(', '); |
| 35 | + |
| 36 | + accept('error', `The ${kind} ${invalidTemplateExpressionsString} cannot be interpreted.`, { |
| 37 | + node: findFirstAnnotationCallOf(node, builtinAnnotations.PythonCall)!, |
| 38 | + property: 'annotation', |
| 39 | + code: CODE_PYTHON_CALL_INVALID_TEMPLATE_EXPRESSION, |
| 40 | + }); |
| 41 | + } |
| 42 | + }; |
| 43 | +}; |
0 commit comments