nitj: implement ACastExprs
authorAlexandre Terrasa <alexandre@moz-code.org>
Mon, 13 Jul 2015 21:04:21 +0000 (17:04 -0400)
committerAlexandre Terrasa <alexandre@moz-code.org>
Tue, 21 Jul 2015 21:23:22 +0000 (17:23 -0400)
Signed-off-by: Alexandre Terrasa <alexandre@moz-code.org>

src/compiler/java_compiler.nit

index 8f8faa3..4469b38 100644 (file)
@@ -717,6 +717,13 @@ class JavaCompilerVisitor
        # Used by aborts, asserts, casts, etc.
        fun add_abort(message: String) do
                add("System.err.print(\"Runtime error: {message}\");")
+               add_raw_abort
+       end
+
+       # Abort without displaying the cause.
+       #
+       # Used to customizable errors.
+       private fun add_raw_abort do
                var node = current_node
                if node != null then
                        add("System.err.print(\" ({node.location.short_location})\");")
@@ -725,6 +732,15 @@ class JavaCompilerVisitor
                add("System.exit(1);")
        end
 
+       # Add a dynamic cast
+       fun add_cast(value: RuntimeVariable, mtype: MType) do
+               var res = type_test(value, mtype)
+               add("if (!{res}) \{")
+               add("System.err.print(\"Runtime error: Cast failed. Expected `{mtype.to_s.escape_to_c}`, got `\" + {value}.rtclass.class_name + \"`\");")
+               add_raw_abort
+               add("\}")
+       end
+
        # Types handling
 
        # Anchor a type to the main module and the current receiver
@@ -2175,6 +2191,27 @@ redef class ANullExpr
        redef fun expr(v) do return v.null_instance
 end
 
+redef class AAsCastExpr
+       redef fun expr(v)
+       do
+               var i = v.expr(n_expr, null)
+               v.add_cast(i, mtype.as(not null))
+               return i
+       end
+end
+
+redef class AAsNotnullExpr
+       redef fun expr(v) do
+               var i = v.expr(n_expr, null)
+               if i.mtype.is_java_primitive then return i
+
+               v.add("if ({i} == null || {i}.is_null()) \{")
+               v.add_abort("Cast failed")
+               v.add("\}")
+               return i
+       end
+end
+
 redef class AIsaExpr
        redef fun expr(v)
        do