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: allow any widening/narrowing type cast #948

Merged
merged 1 commit into from
Mar 26, 2024
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
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;
}