Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: stricter definition of const parameters #776

Merged
merged 4 commits into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ export class SafeDsPartialEvaluator {
this.cache = new WorkspaceCache(services.shared);
}

// -----------------------------------------------------------------------------------------------------------------
// evaluate
// -----------------------------------------------------------------------------------------------------------------

evaluate(node: AstNode | undefined): EvaluatedNode {
return this.evaluateWithSubstitutions(node, NO_SUBSTITUTIONS)?.unwrap();
}
Expand Down Expand Up @@ -501,6 +505,46 @@ export class SafeDsPartialEvaluator {
// else -> undefined
// }
// }

// -----------------------------------------------------------------------------------------------------------------
// canBeValueOfConstantParameter
// -----------------------------------------------------------------------------------------------------------------

/**
* Returns whether the given expression can be the value of a constant parameter.
*/
canBeValueOfConstantParameter = (node: SdsExpression): boolean => {
if (isSdsBoolean(node) || isSdsFloat(node) || isSdsInt(node) || isSdsNull(node) || isSdsString(node)) {
return true;
} else if (isSdsCall(node)) {
// If some arguments are not provided, we already show an error.
return (
this.canBeValueOfConstantParameter(node.receiver) &&
getArguments(node).every((it) => this.canBeValueOfConstantParameter(it.value))
);
} else if (isSdsList(node)) {
return node.elements.every(this.canBeValueOfConstantParameter);
} else if (isSdsMap(node)) {
return node.entries.every(
(it) => this.canBeValueOfConstantParameter(it.key) && this.canBeValueOfConstantParameter(it.value),
);
} else if (isSdsMemberAccess(node)) {
// 1. We cannot allow all member accesses, since we might also access an attribute that has type 'Int', for
// example. Thus, type checking does not always show an error, even though we already restrict the
// possible types of constant parameters.
// 2. If the member cannot be resolved, we already show an error.
// 3. If the enum variant has parameters that are not provided, we already show an error.
const member = node.member?.target?.ref;
return !member || isSdsEnumVariant(member);
} else if (isSdsPrefixOperation(node)) {
return node.operator === '-' && this.canBeValueOfConstantParameter(node.operand);
} else if (isSdsReference(node)) {
// If the reference cannot be resolved, we already show an error.
return !node.target.ref;
} else {
return false;
}
};
}

const NO_SUBSTITUTIONS: ParameterSubstitutions = new Map();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getContainerOfType } from 'langium';
import type { SafeDsClasses } from '../builtins/safe-ds-classes.js';
import { isSdsEnum, type SdsAbstractResult, SdsDeclaration } from '../generated/ast.js';
import { getParameters, Parameter } from '../helpers/nodeProperties.js';
import { Enum, EnumVariant, getParameters, Parameter } from '../helpers/nodeProperties.js';
import { Constant } from '../partialEvaluation/model.js';
import { SafeDsServices } from '../safe-ds-module.js';
import {
Expand Down Expand Up @@ -34,10 +34,14 @@ export class SafeDsTypeChecker {
this.typeComputer = () => services.types.TypeComputer;
}

// -----------------------------------------------------------------------------------------------------------------
// isAssignableTo
// -----------------------------------------------------------------------------------------------------------------

/**
* Checks whether {@link type} is assignable {@link other}.
*/
isAssignableTo(type: Type, other: Type): boolean {
isAssignableTo = (type: Type, other: Type): boolean => {
if (type === UnknownType || other === UnknownType) {
return false;
} else if (other instanceof UnionType) {
Expand All @@ -63,7 +67,7 @@ export class SafeDsTypeChecker {
} /* c8 ignore start */ else {
throw new Error(`Unexpected type: ${type.constructor.name}`);
} /* c8 ignore stop */
}
};

private callableTypeIsAssignableTo(type: CallableType, other: Type): boolean {
if (other instanceof ClassType) {
Expand Down Expand Up @@ -254,4 +258,31 @@ export class SafeDsTypeChecker {
private unionTypeIsAssignableTo(type: UnionType, other: Type): boolean {
return type.possibleTypes.every((it) => this.isAssignableTo(it, other));
}

// -----------------------------------------------------------------------------------------------------------------
// canBeTypeOfConstantParameter
// -----------------------------------------------------------------------------------------------------------------

/**
* Checks whether {@link type} is allowed as the type of a constant parameter.
*/
canBeTypeOfConstantParameter = (type: Type): boolean => {
if (type instanceof ClassType) {
return [
this.builtinClasses.Boolean,
this.builtinClasses.Float,
this.builtinClasses.Int,
this.builtinClasses.List,
this.builtinClasses.Map,
this.builtinClasses.Nothing,
this.builtinClasses.String,
].includes(type.declaration);
} else if (type instanceof EnumType) {
return Enum.isConstant(type.declaration);
} else if (type instanceof EnumVariantType) {
return EnumVariant.isConstant(type.declaration);
} else {
return type instanceof LiteralType || type === UnknownType;
}
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
getResults,
Parameter,
} from '../../../helpers/nodeProperties.js';
import { SafeDsServices } from '../../../safe-ds-module.js';
import type { SafeDsServices } from '../../../safe-ds-module.js';

export const CODE_ANNOTATION_CALL_CONSTANT_ARGUMENT = 'annotation-call/constant-argument';
export const CODE_ANNOTATION_CALL_MISSING_ARGUMENT_LIST = 'annotation-call/missing-argument-list';
Expand All @@ -28,10 +28,8 @@ export const annotationCallArgumentsMustBeConstant = (services: SafeDsServices)

return (node: SdsAnnotationCall, accept: ValidationAcceptor) => {
for (const argument of getArguments(node)) {
const evaluatedArgumentValue = partialEvaluator.evaluate(argument.value);

if (!evaluatedArgumentValue.isFullyEvaluated) {
accept('error', 'Arguments of annotation calls must be constant.', {
if (!partialEvaluator.canBeValueOfConstantParameter(argument.value)) {
accept('error', 'Values assigned to annotation parameters must be constant.', {
node: argument,
property: 'value',
code: CODE_ANNOTATION_CALL_CONSTANT_ARGUMENT,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { getContainerOfType, ValidationAcceptor } from 'langium';
import { isSdsAnnotation, isSdsCallable, SdsParameter } from '../../../generated/ast.js';
import { Enum, EnumVariant, Parameter } from '../../../helpers/nodeProperties.js';
import { Parameter } from '../../../helpers/nodeProperties.js';
import { SafeDsServices } from '../../../safe-ds-module.js';
import { ClassType, EnumType, EnumVariantType, LiteralType, type Type, UnknownType } from '../../../typing/model.js';

export const CODE_PARAMETER_CONSTANT_DEFAULT_VALUE = 'parameter/constant-default-value';
export const CODE_PARAMETER_CONSTANT_TYPE = 'parameter/constant-type';
Expand All @@ -11,10 +10,11 @@ export const constantParameterMustHaveConstantDefaultValue = (services: SafeDsSe
const partialEvaluator = services.evaluation.PartialEvaluator;

return (node: SdsParameter, accept: ValidationAcceptor) => {
if (!Parameter.isConstant(node) || !node.defaultValue) return;
if (!Parameter.isConstant(node) || !node.defaultValue) {
return;
}

const evaluatedDefaultValue = partialEvaluator.evaluate(node.defaultValue);
if (!evaluatedDefaultValue.isFullyEvaluated) {
if (!partialEvaluator.canBeValueOfConstantParameter(node.defaultValue)) {
const containingCallable = getContainerOfType(node, isSdsCallable);
const kind = isSdsAnnotation(containingCallable) ? 'annotation' : 'constant';

Expand All @@ -28,7 +28,7 @@ export const constantParameterMustHaveConstantDefaultValue = (services: SafeDsSe
};

export const constantParameterMustHaveTypeThatCanBeEvaluatedToConstant = (services: SafeDsServices) => {
const isConstantType = isConstantTypeProvider(services);
const typeChecker = services.types.TypeChecker;
const typeComputer = services.types.TypeComputer;

return (node: SdsParameter, accept: ValidationAcceptor) => {
Expand All @@ -37,32 +37,15 @@ export const constantParameterMustHaveTypeThatCanBeEvaluatedToConstant = (servic
}

const type = typeComputer.computeType(node);
if (!isConstantType(type)) {
accept(
'error',
`The parameter must be a constant but type '${type.toString()}' cannot be evaluated to a constant.`,
{
node,
property: 'type',
code: CODE_PARAMETER_CONSTANT_TYPE,
},
);
}
};
};

const isConstantTypeProvider = (services: SafeDsServices) => {
const builtinClasses = services.builtins.Classes;
if (!typeChecker.canBeTypeOfConstantParameter(type)) {
const containingCallable = getContainerOfType(node, isSdsCallable);
const kind = isSdsAnnotation(containingCallable) ? 'An annotation' : 'A constant';

return (type: Type): boolean => {
if (type instanceof ClassType) {
return builtinClasses.isBuiltinClass(type.declaration);
} else if (type instanceof EnumType) {
return Enum.isConstant(type.declaration);
} else if (type instanceof EnumVariantType) {
return EnumVariant.isConstant(type.declaration);
} else {
return type instanceof LiteralType || type === UnknownType;
accept('error', `${kind} parameter cannot have type '${type.toString()}'.`, {
node,
property: 'type',
code: CODE_PARAMETER_CONSTANT_TYPE,
});
}
};
};
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
import { ValidationAcceptor } from 'langium';
import { SdsCall } from '../../../generated/ast.js';
import { type SdsCall } from '../../../generated/ast.js';
import { getArguments, Parameter } from '../../../helpers/nodeProperties.js';
import { SafeDsServices } from '../../../safe-ds-module.js';

export const CODE_CALL_CONSTANT_ARGUMENT = 'call/constant-argument';

export const callArgumentsMustBeConstantIfParameterIsConstant = (services: SafeDsServices) => {
export const callArgumentMustBeConstantIfParameterIsConstant = (services: SafeDsServices) => {
const nodeMapper = services.helpers.NodeMapper;
const partialEvaluator = services.evaluation.PartialEvaluator;

return (node: SdsCall, accept: ValidationAcceptor) => {
for (const argument of getArguments(node)) {
if (!argument.value) {
/* c8 ignore next 2 */
return;
}

const parameter = nodeMapper.argumentToParameter(argument);
if (!Parameter.isConstant(parameter)) continue;
if (!Parameter.isConstant(parameter)) {
return;
}

const evaluatedArgumentValue = partialEvaluator.evaluate(argument.value);
if (!evaluatedArgumentValue.isFullyEvaluated) {
accept('error', 'Arguments assigned to constant parameters must be constant.', {
if (!partialEvaluator.canBeValueOfConstantParameter(argument.value)) {
accept('error', 'Values assigned to constant parameters must be constant.', {
node: argument,
property: 'value',
code: CODE_CALL_CONSTANT_ARGUMENT,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ import {
typeParameterMustHaveSufficientContext,
typeParameterMustNotBeUsedInNestedNamedTypeDeclarations,
} from './other/declarations/typeParameters.js';
import { callArgumentsMustBeConstantIfParameterIsConstant } from './other/expressions/calls.js';
import { callArgumentMustBeConstantIfParameterIsConstant } from './other/expressions/calls.js';
import { divisionDivisorMustNotBeZero } from './other/expressions/infixOperations.js';
import {
lambdaMustBeAssignedToTypedParameter,
Expand Down Expand Up @@ -223,7 +223,7 @@ export const registerValidationChecks = function (services: SafeDsServices) {
SdsBlockLambda: [blockLambdaMustContainUniqueNames],
SdsCall: [
callArgumentListShouldBeNeeded(services),
callArgumentsMustBeConstantIfParameterIsConstant(services),
callArgumentMustBeConstantIfParameterIsConstant(services),
callReceiverMustBeCallable(services),
],
SdsCallableType: [
Expand Down
Loading