Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Catch impossible default values at compile time.
When we use a literal as a default value, we know its type. We can
check it against any declared nominal type, and complain at compile
time that it's unreasonable.
  • Loading branch information
jnthn committed Jun 30, 2015
1 parent 7c35c5e commit 6519911
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/Perl6/Actions.nqp
Expand Up @@ -3881,7 +3881,24 @@ Compilation unit '$file' contained the following violations:
}
my $val := $<default_value>[0].ast;
if $val.has_compile_time_value {
%*PARAM_INFO<default_value> := $val.compile_time_value;
my $value := $val.compile_time_value;
if nqp::existskey(%*PARAM_INFO, 'nominal_type') {
my $expected := %*PARAM_INFO<nominal_type>;
unless nqp::istype($value, $expected) {
# Ensure both types are composed before complaining,
# or we give spurious errors on stubbed things or
# things we're in the middle of compiling.
my $got_comp := try $value.HOW.is_composed($value);
my $exp_comp := try $expected.HOW.is_composed($expected);
if $got_comp && $exp_comp {
$<default_value>[0].CURSOR.typed_sorry(
'X::Parameter::Default::TypeCheck',
got => $value,
expected => %*PARAM_INFO<nominal_type>);
}
}
}
%*PARAM_INFO<default_value> := $value;
%*PARAM_INFO<default_is_literal> := 1;
}
else {
Expand Down
8 changes: 8 additions & 0 deletions src/core/Exception.pm
Expand Up @@ -831,6 +831,14 @@ my class X::Parameter::Default does X::Comp {
}
}

my class X::Parameter::Default::TypeCheck does X::Comp {
has $.got;
has $.expected;
method message() {
"Default value '$.got.gist()' will never bind to a parameter of type $.expected.^name()"
}
}

my class X::Parameter::AfterDefault does X::Syntax {
has $.type;
has $.modifier;
Expand Down

0 comments on commit 6519911

Please sign in to comment.