Skip to content

Commit

Permalink
feat: allow any widening/narrowing type cast
Browse files Browse the repository at this point in the history
  • Loading branch information
lars-reimann committed Mar 26, 2024
1 parent 114fee6 commit 5f7d8b9
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
12 changes: 10 additions & 2 deletions packages/safe-ds-lang/src/language/validation/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,12 +354,20 @@ export const prefixOperationOperandMustHaveCorrectType = (services: SafeDsServic
};

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

return (node: SdsTypeCast, accept: ValidationAcceptor): void => {
const expressionType = typeComputer.computeType(node.expression);
if (node.expression && expressionType !== UnknownType) {
accept('error', 'Type casts can only be applied to expressions of unknown type.', {
const targetType = typeComputer.computeType(node.type);

if (
node.expression &&
expressionType !== UnknownType &&
!typeChecker.isSubtypeOf(expressionType, targetType) &&
!typeChecker.isSupertypeOf(expressionType, targetType)
) {
accept('error', 'This type cast can never succeed.', {
// Using property: "expression" does not work here, probably due to eclipse-langium/langium#1218
node: node.expression,
code: CODE_TYPE_MISMATCH,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
package tests.validation.types.checking.typeCasts

class C()
class D() sub C
class E() sub C

pipeline test {
// $TEST$ no error "Type casts can only be applied to expressions of unknown type."
»unresolved« as Int;
// $TEST$ error "This type cast can never succeed."
»D()« as E;

// $TEST$ no error "This type cast can never succeed."
»C()« as C;

// $TEST$ error "Type casts can only be applied to expressions of unknown type."
»1« as Int;
// $TEST$ no error "This type cast can never succeed."
»C()« as D;

// $TEST$ no error "This type cast can never succeed."
»D()« as C;

// $TEST$ no error "This type cast can never succeed."
»unresolved« as Int;
}

0 comments on commit 5f7d8b9

Please sign in to comment.