nitj: implement aborts
authorAlexandre Terrasa <alexandre@moz-code.org>
Fri, 17 Jul 2015 18:06:57 +0000 (14:06 -0400)
committerAlexandre Terrasa <alexandre@moz-code.org>
Tue, 21 Jul 2015 21:23:20 +0000 (17:23 -0400)
Signed-off-by: Alexandre Terrasa <alexandre@moz-code.org>

src/compiler/java_compiler.nit

index 2521c08..d166f63 100644 (file)
@@ -333,17 +333,24 @@ class JavaCompilerVisitor
        # Compile a statement (if any)
        fun stmt(nexpr: nullable AExpr) do
                if nexpr == null then return
+               var old = self.current_node
+               current_node = nexpr
                nexpr.stmt(self)
+               current_node = old
        end
 
        # Compile an expression an return its result
        # `mtype` is the expected return type, pass null if no specific type is expected.
        fun expr(nexpr: AExpr, mtype: nullable MType): RuntimeVariable do
+               var old = current_node
+               current_node = nexpr
+
                var res = null
                if nexpr.mtype != null then
                        res = nexpr.expr(self)
                end
                assert res != null
+               current_node = old
                return res
        end
 
@@ -363,6 +370,19 @@ class JavaCompilerVisitor
                return res
        end
 
+       # Generate generic abort
+       #
+       # Used by aborts, asserts, casts, etc.
+       fun add_abort(message: String) do
+               add("System.err.print(\"Runtime error: {message}\");")
+               var node = current_node
+               if node != null then
+                       add("System.err.print(\" ({node.location.short_location})\");")
+               end
+               add("System.err.println(\"\");")
+               add("System.exit(1);")
+       end
+
        # Display a info message
        fun info(str: String) do compiler.modelbuilder.toolcontext.info(str, 0)
 end
@@ -519,6 +539,15 @@ class JavaStaticFrame
        var returnlabel: nullable String = null is writable
 end
 
+redef class Location
+       # Return a shortened version of the location with `"{file}:{line_start}"`
+       fun short_location: String do
+               var file = self.file
+               if file == null then return "<no file>:{line_start}"
+               return "{file.filename.escape_to_c}:{line_start}"
+       end
+end
+
 redef class MType
        # Return the Java type associated to a given Nit static type
        fun java_type: String do return "RTVal"
@@ -719,6 +748,10 @@ redef class ABlockExpr
        end
 end
 
+redef class AAbortExpr
+       redef fun stmt(v) do v.add_abort("Aborted")
+end
+
 redef class ADebugTypeExpr
        redef fun stmt(v) do end # do nothing
 end