Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Implement coercion between int/num/str.
  • Loading branch information
jnthn committed Jan 12, 2013
1 parent 45359ee commit 2214f2e
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 3 deletions.
40 changes: 38 additions & 2 deletions lib/QAST/JASTCompiler.nqp
Expand Up @@ -217,8 +217,7 @@ class QAST::OperationsJAST {
while $i < $expected_args {
my $type := @stack_in[$i];
my $operand := $node[$i];
my $operand_res := $qastcomp.as_jast($node[$i]);
# XXX coercion...
my $operand_res := $qastcomp.as_jast($node[$i], :want($type));
$il.append($operand_res.jast);
$i++;
nqp::push(@arg_res, $operand_res);
Expand Down Expand Up @@ -2109,6 +2108,43 @@ class QAST::CompilerJAST {
elsif $desired == $RT_VOID {
$il.append(pop_ins($got));
}
elsif $desired == $RT_INT {
if $got == $RT_NUM {
$il.append(JAST::Instruction.new( :op('d2l') ));
}
elsif $got == $RT_STR {
$il.append(JAST::Instruction.new( :op('invokestatic'),
$TYPE_OPS, 'coerce_s2i', 'Long', $TYPE_STR ));
}
else {
nqp::die("Auto-unboxing NYI");
}
}
elsif $desired == $RT_NUM {
if $got == $RT_INT {
$il.append(JAST::Instruction.new( :op('l2d') ));
}
elsif $got == $RT_STR {
$il.append(JAST::Instruction.new( :op('invokestatic'),
$TYPE_OPS, 'coerce_s2n', 'Double', $TYPE_STR ));
}
else {
nqp::die("Auto-unboxing NYI");
}
}
elsif $desired == $RT_STR {
if $got == $RT_INT {
$il.append(JAST::Instruction.new( :op('invokestatic'),
$TYPE_OPS, 'coerce_i2s', $TYPE_STR, 'Long' ));
}
elsif $got == $RT_NUM {
$il.append(JAST::Instruction.new( :op('invokestatic'),
$TYPE_OPS, 'coerce_n2s', $TYPE_STR, 'Double' ));
}
else {
nqp::die("Auto-unboxing NYI");
}
}
else {
nqp::die("Coercion from type '$got' to '$desired' NYI");
}
Expand Down
26 changes: 25 additions & 1 deletion src/org/perl6/nqp/runtime/Ops.java
Expand Up @@ -882,4 +882,28 @@ public static SixModelObject sethllconfig(String language, SixModelObject config
config.slurpyHashType = configHash.at_key_boxed(tc, "slurpy_hash");
return configHash;
}
}

/* Coercions. */
public static long coerce_s2i(String in) {
try {
return Long.parseLong(in);
}
catch (NumberFormatException e) {
return 0;
}
}
public static double coerce_s2n(String in) {
try {
return Double.parseDouble(in);
}
catch (NumberFormatException e) {
return 0.0;
}
}
public static String coerce_i2s(long in) {
return Long.toString(in);
}
public static String coerce_n2s(double in) {
return Double.toString(in);
}
}

0 comments on commit 2214f2e

Please sign in to comment.