compile: implicit isset for attribute read access
[nit.git] / src / compiling / compiling_methods.nit
index ed0c4ab..61f3267 100644 (file)
@@ -24,6 +24,8 @@ redef class CompilerVisitor
        # Compile a statment node
        meth compile_stmt(n: PExpr)
        do
+               if n == null then return
+               #add_instr("/* Compile stmt {n.locate} */")
                n.prepare_compile_stmt(self)
                var i = cfc._variable_index
                n.compile_stmt(self)
@@ -33,25 +35,27 @@ redef class CompilerVisitor
        # Compile is expression node
        meth compile_expr(n: PExpr): String
        do
+               #add_instr("/* Compile expr {n.locate} */")
                var i = cfc._variable_index
                var s = n.compile_expr(self)
                cfc._variable_index = i
-               if s[0] == ' ' then
+               if s[0] == ' ' or cfc.is_valid_variable(s) then
                        return s
                end
-               var v = cfc.get_var
+               var v = cfc.get_var("Result")
                add_assignment(v, s)
                return v
        end
 
        # Ensure that a c expression is a var
-       meth ensure_var(s: String): String
+       meth ensure_var(s: String, comment: String): String
        do
-               if s.substring(0,3) == "variable" then
+               if cfc.is_valid_variable(s) then
+                       add_instr("/* Ensure var {s}: {comment}*/")
                        return s
                end
-               var v = cfc.get_var
-               add_assignment(v, s)
+               var v = cfc.get_var(null)
+               add_assignment(v, "{s} /* Ensure var: {comment}*/")
                return v
        end
 
@@ -73,17 +77,12 @@ redef class CompilerVisitor
        # Generate an fprintf to display an error location
        meth printf_locate_error(node: PNode): String
        do
-               var s = "fprintf(stderr, \""
+               var s = new Buffer.from("fprintf(stderr, \"")
                if nmc != null then s.append(" in %s")
                s.append(" (%s:%d)\\n\", ")
                if nmc != null then s.append("LOCATE_{nmc.method.cname}, ")
                s.append("LOCATE_{module.name}, {node.line_number});")
-               return s
-       end
-
-       redef init(module: MMSrcModule)
-       do
-               super
+               return s.to_s
        end
 
        meth invoke_super_init_calls_after(start_prop: MMMethod)
@@ -126,7 +125,7 @@ redef class CompilerVisitor
                                end
                        end
                        #s.append(" {p}")
-                       p.compile_call(self, cargs)
+                       p.compile_stmt_call(self, cargs)
                        i += 1
                end
                #s.append(" ]")
@@ -149,37 +148,40 @@ class CFunctionContext
        # Total number of variable
        attr _variable_index_max: Int = 0
 
-       # Association between nit variable and the corrsponding c variable
-       attr _varnames: Map[Variable, String] = new HashMap[Variable, String]
+       # Association between nit variable and the corrsponding c variable index
+       attr _varindexes: Map[Variable, Int] = new HashMap[Variable, Int]
 
        # Are we currenlty in a closure definition?
-       readable writable attr _in_closure: Bool = false
+       readable writable attr _closure: NitMethodContext = null
 
+       # Return the cvariable of a Nit variable
        meth varname(v: Variable): String
        do
-               if _in_closure then
-                       return "closctx->{_varnames[v]}"
+               if v isa ClosureVariable then
+                       return closure_variable(_varindexes[v])
                else
-                       return _varnames[v]
+                       return variable(_varindexes[v])
                end
        end
 
        # Return the next available variable
-       meth get_var: String
+       meth get_var(comment: String): String
        do
                var v = variable(_variable_index)
                _variable_index = _variable_index + 1
                if _variable_index > _variable_index_max then
-                       #visitor.add_decl("val_t {v};")
                        _variable_index_max = _variable_index 
                end
+               if comment != null then
+                       visitor.add_instr("/* Register {v}: {comment} */")
+               end
                return v
        end
 
        meth register_variable(v: Variable): String
        do
-               var s = get_var
-               _varnames[v] = "variable[{_variable_index-1}]"
+               _varindexes[v] = _variable_index
+               var s = get_var("Local variable")
                return s
        end
 
@@ -189,25 +191,56 @@ class CFunctionContext
        meth register_closurevariable(v: ClosureVariable): String
        do
                var s = "closurevariable[{_closurevariable_index}]"
+               _varindexes[v] = _closurevariable_index
                _closurevariable_index += 1
-               _varnames[v] = s
-               if _in_closure then
+               if _closure != null then
                        return "(closctx->{s})"
                else
                        return s
                end
        end
 
-       # Return the ith variable
+       # Return the ith cvariable
        protected meth variable(i: Int): String
        do
-               if _in_closure then
-                       return "(closctx->variable[{i}])"
+               if closure != null then
+                       var vn = once new Array[String]
+                       if vn.length <= i then
+                               for j in [vn.length..i] do
+                                       vn[j] = "(closctx->variable[{j}])"
+                               end
+                       end
+                       return vn[i]
+               else
+                       var vn = once new Array[String]
+                       if vn.length <= i then
+                               for j in [vn.length..i] do
+                                       vn[j] = "variable[{j}]"
+                               end
+                       end
+                       return vn[i]
+               end
+       end
+
+       # Return the ith closurevariable
+       protected meth closure_variable(i: Int): String
+       do
+               if closure != null then
+                       return "(closctx->closurevariable[{i}])"
                else
-                       return "variable[{i}]"
+                       return "closurevariable[{i}]"
                end
        end
 
+       # Is s a valid variable
+       protected meth is_valid_variable(s: String): Bool
+       do
+               for i in [0.._variable_index[ do
+                       if s == variable(i) then return true
+               end
+               return false
+       end
+
        # Mark the variable available
        meth free_var(v: String)
        do
@@ -227,9 +260,9 @@ class CFunctionContext
                        visitor.add_decl("val_t *variable = NULL;")
                end
                if _closurevariable_index > 0 then
-                       visitor.add_decl("void *closurevariable[{_closurevariable_index}];")
+                       visitor.add_decl("struct WBT_ *closurevariable[{_closurevariable_index}];")
                else
-                       visitor.add_decl("void **closurevariable = NULL;")
+                       visitor.add_decl("struct WBT_ **closurevariable = NULL;")
                end
        end
 
@@ -275,11 +308,30 @@ redef class ClosureVariable
 end
 
 redef class MMMethod
+       # Compile as an expression.
+       # require that signature.return_type != null
+       meth compile_expr_call(v: CompilerVisitor, cargs: Array[String]): String
+       do
+               assert signature.return_type != null
+               var s = intern_compile_call(v, cargs)
+               assert s != null
+               return s
+       end
+
+       # Compile as a statement.
+       # require that signature.return_type == null
+       meth compile_stmt_call(v: CompilerVisitor, cargs: Array[String])
+       do
+               assert signature.return_type == null
+               var s = intern_compile_call(v, cargs)
+               assert s == null
+       end
+
        # Compile a call on self for given arguments
        # Most calls are compiled with a table access,
        # primitive calles are inlined
        # == and != are guarded and possibly inlined
-       meth compile_call(v: CompilerVisitor, cargs: Array[String]): String
+       private meth intern_compile_call(v: CompilerVisitor, cargs: Array[String]): String
        do
                var i = self
                if i isa MMSrcMethod then
@@ -294,7 +346,7 @@ redef class MMMethod
                var ne = once "!=".to_symbol
                if name == ne then
                        var eqp = signature.recv.local_class.select_method(ee)
-                       var eqcall = eqp.compile_call(v, cargs)
+                       var eqcall = eqp.compile_expr_call(v, cargs)
                        return "TAG_Bool(!UNTAG_Bool({eqcall}))"
                end
                if global.is_init then
@@ -320,12 +372,70 @@ redef class MMMethod
                end
        end
 
+       # Compile a call on self for given arguments and given closures
+       meth compile_call_and_closures(v: CompilerVisitor, cargs: Array[String], clos_defs: Array[PClosureDef]): String
+       do
+               var ve: String = null
+               var arity = 0
+               if clos_defs != null then arity = clos_defs.length
+
+               # Prepare result value.
+               # In case of procedure, the return value is still used to intercept breaks
+               var old_bv = v.nmc.break_value
+               ve = v.cfc.get_var("Closure return value and escape marker")
+               v.nmc.break_value = ve
+
+               # Compile closure to c function
+               var realcargs = new Array[String] # Args to pass to the C function call
+               var closcns = new Array[String] # Closure C structure names
+               realcargs.add_all(cargs)
+               for i in [0..arity[ do
+                       var cn = clos_defs[i].compile_closure(v, closure_cname(i))
+                       closcns.add(cn)
+                       realcargs.add(cn)
+               end
+               for i in [arity..signature.closures.length[ do
+                       realcargs.add("NULL")
+               end
+
+               v.nmc.break_value = old_bv
+
+               # Call
+               var e = intern_compile_call(v, realcargs)
+               if e != null then
+                       v.add_assignment(ve, e)
+                       e = ve
+               end
+
+               # Intercept returns and breaks
+               for i in [0..arity[ do
+                       # A break or a return is intercepted
+                       v.add_instr("if ({closcns[i]}->has_broke != NULL) \{")
+                       v.indent
+                       # A passtrought break or a return is intercepted: go the the next closure
+                       v.add_instr("if ({closcns[i]}->has_broke != &({ve})) \{")
+                       v.indent
+                       if v.cfc.closure == v.nmc then v.add_instr("closctx->has_broke = {closcns[i]}->has_broke; closctx->broke_value = {closcns[i]}->broke_value;")
+                       v.add_instr("goto {v.nmc.return_label};")
+                       v.unindent
+                       # A direct break is interpected
+                       if e != null then
+                               # overwrite the returned value in a function
+                               v.add_instr("\} else {ve} = {closcns[i]}->broke_value;")
+                       else
+                               # Do nothing in a procedure
+                               v.add_instr("\}")
+                       end
+                       v.unindent
+                       v.add_instr("\}")
+               end
+               return e
+       end
+
        # Compile a call as constructor with given args
        meth compile_constructor_call(v: CompilerVisitor, recvtype: MMType, cargs: Array[String]): String
        do
-               var recv = v.cfc.get_var
-               v.add_instr("{recv} = NEW_{recvtype.local_class}_{global.intro.cname}({cargs.join(", ")}); /*new {recvtype}*/")
-               return recv
+               return "NEW_{recvtype.local_class}_{global.intro.cname}({cargs.join(", ")}) /*new {recvtype}*/"
        end
 
        # Compile a call as call-next-method on self with given args
@@ -339,16 +449,26 @@ redef class MMMethod
        # Cname of the i-th closure C struct type
        protected meth closure_cname(i: Int): String
        do
-               return "WBT_{cname}_{i}"
+               return "FWBT_{cname}_{i}"
        end
 end
 
 redef class MMAttribute
-       # Compile an acces on selffor a given reciever.
-       # Result is a valid C left-value for assigment
-       meth compile_access(v: CompilerVisitor, recv: String): String
+       # Compile a read acces on selffor a given reciever.
+       meth compile_read_access(v: CompilerVisitor, n: PNode, recv: String): String
+       do
+               var res = "{global.attr_access}({recv}) /*{local_class}::{name}*/"
+               if not signature.return_type.is_nullable and v.tc.opt_warn.value > 0 then
+                       res = v.ensure_var(res, "{local_class}::{name}")
+                       v.add_instr("if ({res} == NIT_NULL) \{ fprintf(stderr, \"Uninitialized attribute %s\", \"{name}\"); {v.printf_locate_error(n)} } /* implicit isset */;")
+               end
+               return res
+       end
+
+       # Compile a write acces on selffor a given reciever.
+       meth compile_write_access(v: CompilerVisitor, n: PNode, recv: String, value: String)
        do
-               return "{global.attr_access}({recv}) /*{local_class}::{name}*/"
+               v.add_instr("{global.attr_access}({recv}) /*{local_class}::{name}*/ = {value};")
        end
 end
 
@@ -374,17 +494,15 @@ redef class MMSrcMethod
                        var closcn = closure_cname(i)
                        var cs = signature.closures[i].signature # Closure signature
                        var subparams = new Array[String] # Parameters of the closure
-                       subparams.add("struct {closcn}*")
+                       subparams.add("struct WBT_ *")
                        for j in [0..cs.arity[ do
                                var p = "val_t"
                                subparams.add(p)
                        end
                        var r = "void"
                        if cs.return_type != null then r = "val_t"
-                       params.add("struct {closcn} *{args[first_closure_index+i]}")
-                       v.add_decl("struct {closcn};")
-                       v.add_decl("typedef {r} (*F{closcn})({subparams.join(", ")});")
-                       v.add_decl("struct {closcn} \{F{closcn} fun; val_t *has_broke; val_t broke_value; val_t *variable; void **closurevariable;\};")
+                       params.add("struct WBT_ *{args[first_closure_index+i]}")
+                       v.add_decl("typedef {r} (*{closcn})({subparams.join(", ")});")
                end
 
                if global.is_init then
@@ -458,14 +576,14 @@ end
 redef class MMReadImplementationMethod
        redef meth do_compile_inside(v, params)
        do
-               return node.prop.compile_access(v, params[0])
+               return node.prop.compile_read_access(v, node, params[0])
        end
 end
 
 redef class MMWriteImplementationMethod
        redef meth do_compile_inside(v, params)
        do
-               v.add_assignment(node.prop.compile_access(v, params[0]), params[1])
+               node.prop.compile_write_access(v, node, params[0], params[1])
                return null
        end
 end
@@ -491,14 +609,14 @@ redef class MMImplicitInit
                                for i in [1..f[ do
                                        args.add(params[i])
                                end
-                               sp.compile_call(v, args)
+                               sp.compile_stmt_call(v, args)
                        else
-                               sp.compile_call(v, args_recv)
+                               sp.compile_stmt_call(v, args_recv)
                        end
                end
                for i in [f..params.length[ do
                        var attribute = unassigned_attributes[i-f]
-                       v.add_assignment(attribute.compile_access(v, recv), params[i])
+                       attribute.compile_write_access(v, null, recv, params[i])
                end
                return null
        end
@@ -507,19 +625,49 @@ end
 redef class MMType
        # Compile a subtype check to self
        # Return a NIT Bool
-       meth compile_cast(v: CompilerVisitor, recv: String): String
+       meth compile_cast(v: CompilerVisitor, recv: String, fromtype: MMType): String
        do
                # Fixme: handle formaltypes
                var g = local_class.global
-               return "TAG_Bool(({recv}==NIT_NULL) || VAL_ISA({recv}, {g.color_id}, {g.id_id})) /*cast {self}*/"
+               var s = ""
+               if fromtype.is_nullable then
+                       if self.is_nullable then
+                               s = "({recv}==NIT_NULL) || "
+                       else
+                               s = "({recv}!=NIT_NULL) && "
+                       end
+               else
+                       # FIXME This is used to not break code without the nullable KW
+                       s = "({recv}==NIT_NULL) || "
+               end
+               return "TAG_Bool({s}VAL_ISA({recv}, {g.color_id}, {g.id_id})) /*cast {self}*/"
        end
 
        # Compile a cast assertion
-       meth compile_type_check(v: CompilerVisitor, recv: String, n: PNode)
+       meth compile_type_check(v: CompilerVisitor, recv: String, n: PNode, fromtype: MMType)
        do
                # Fixme: handle formaltypes
                var g = local_class.global
-               v.add_instr("if (({recv}!=NIT_NULL) && !VAL_ISA({recv}, {g.color_id}, {g.id_id})) \{ fprintf(stderr, \"Cast failled\"); {v.printf_locate_error(n)} nit_exit(1); } /*cast {self}*/;")
+               var s = ""
+               if fromtype.is_nullable then
+                       if self.is_nullable then
+                               s = "({recv}!=NIT_NULL) && "
+                       else
+                               s = "({recv}==NIT_NULL) || "
+                       end
+               else
+                       # FIXME This is used to not break code without the nullable KW
+                       s = "({recv}!=NIT_NULL) && "
+               end
+               v.add_instr("if ({s}!VAL_ISA({recv}, {g.color_id}, {g.id_id})) \{ fprintf(stderr, \"Cast failled\"); {v.printf_locate_error(n)} nit_exit(1); } /*cast {self}*/;")
+       end
+
+       # Compile a notnull cast assertion
+       meth compile_notnull_check(v: CompilerVisitor, recv: String, n: PNode)
+       do
+               if is_nullable then
+                       v.add_instr("if (({recv}==NIT_NULL)) \{ fprintf(stderr, \"Cast failled\"); {v.printf_locate_error(n)} nit_exit(1); } /*cast {self}*/;")
+               end
        end
 end
 
@@ -545,14 +693,14 @@ redef class ASignature
                                # FIXME: do not test always
                                # FIXME: handle formal types
                                v.add_instr("/* check if p<{ap.variable.stype} with p:{orig_type} */")
-                               ap.variable.stype.compile_type_check(v, params[ap.position], ap)
+                               ap.variable.stype.compile_type_check(v, params[ap.position], ap, orig_type)
                        end
                        v.add_assignment(cname, params[ap.position])
                end
                for i in [0..n_closure_decls.length[ do
                        var wd = n_closure_decls[i]
                        var cname = v.cfc.register_closurevariable(wd.variable)
-                       wd.variable.ctypename = "struct {v.nmc.method.closure_cname(i)} *"
+                       wd.variable.ctypename = v.nmc.method.closure_cname(i)
                        v.add_assignment(cname, "{params[orig_sig.arity + i]}")
                end
        end
@@ -583,13 +731,11 @@ redef class AConcreteMethPropdef
                end
 
                v.nmc.return_label = "return_label{v.new_number}"
-               v.nmc.return_value = v.cfc.get_var
+               v.nmc.return_value = v.cfc.get_var("Method return value and escape marker")
                if self isa AConcreteInitPropdef then
                        v.invoke_super_init_calls_after(null)
                end
-               if n_block != null then
-                       v.compile_stmt(n_block)
-               end
+               v.compile_stmt(n_block)
                v.add_instr("{v.nmc.return_label}: while(false);")
                if self isa AConcreteInitPropdef then
                        v.add_instr("init_table[{itpos}] = 1;")
@@ -870,7 +1016,7 @@ redef class AReturnExpr
                        var e = v.compile_expr(n_expr)
                        v.add_assignment(v.nmc.return_value, e)
                end
-               if v.cfc.in_closure then v.add_instr("closctx->has_broke = &({v.nmc.return_value});")
+               if v.cfc.closure == v.nmc then v.add_instr("closctx->has_broke = &({v.nmc.return_value});")
                v.add_instr("goto {v.nmc.return_label};")
        end
 end
@@ -882,7 +1028,7 @@ redef class ABreakExpr
                        var e = v.compile_expr(n_expr)
                        v.add_assignment(v.nmc.break_value, e)
                end
-               if v.cfc.in_closure then v.add_instr("closctx->has_broke = &({v.nmc.break_value}); closctx->broke_value = *closctx->has_broke;")
+               if v.cfc.closure == v.nmc then v.add_instr("closctx->has_broke = &({v.nmc.break_value}); closctx->broke_value = *closctx->has_broke;")
                v.add_instr("goto {v.nmc.break_label};")
        end
 end
@@ -908,9 +1054,7 @@ end
 redef class ADoExpr
        redef meth compile_stmt(v)
        do
-                if n_block != null then
-                        v.compile_stmt(n_block)
-                end
+               v.compile_stmt(n_block)
        end
 end
 
@@ -942,12 +1086,12 @@ redef class AIfexprExpr
                v.add_instr("if (UNTAG_Bool({e})) \{ /*if*/")
                v.cfc.free_var(e)
                v.indent
-               var e = v.ensure_var(v.compile_expr(n_then))
+               var e = v.ensure_var(v.compile_expr(n_then), "Then value")
                v.unindent
                v.add_instr("} else \{ /*if*/")
                v.cfc.free_var(e)
                v.indent
-               var e2 = v.ensure_var(v.compile_expr(n_else))
+               var e2 = v.ensure_var(v.compile_expr(n_else), "Else value")
                v.add_assignment(e, e2)
                v.unindent
                v.add_instr("}")
@@ -955,7 +1099,8 @@ redef class AIfexprExpr
        end
 end
 
-redef class AControlableBlock
+class AControlableBlock
+special PExpr
        meth compile_inside_block(v: CompilerVisitor) is abstract
        redef meth compile_stmt(v)
        do
@@ -974,6 +1119,7 @@ redef class AControlableBlock
 end
 
 redef class AWhileExpr
+special AControlableBlock
        redef meth compile_inside_block(v)
        do
                v.add_instr("while (true) \{ /*while*/")
@@ -981,9 +1127,7 @@ redef class AWhileExpr
                var e = v.compile_expr(n_expr)
                v.add_instr("if (!UNTAG_Bool({e})) break; /* while*/")
                v.cfc.free_var(e)
-               if n_block != null then
-                       v.compile_stmt(n_block)
-               end
+               v.compile_stmt(n_block)
                v.add_instr("{v.nmc.continue_label}: while(0);")
                v.unindent
                v.add_instr("}")
@@ -992,59 +1136,27 @@ redef class AWhileExpr
 end
 
 redef class AForExpr
+special AControlableBlock
        redef meth compile_inside_block(v)
        do
-               v.compile_stmt(n_vardecl)
-       end
-end
-
-redef class AForVardeclExpr
-       redef meth compile_stmt(v)
-       do
                var e = v.compile_expr(n_expr)
-               var prop = n_expr.stype.local_class.select_method(once "iterator".to_symbol)
-               if prop == null then
-                       printl("No iterator")
-                       return
-               end
-               var ittype = prop.signature.return_type
+               var ittype = meth_iterator.signature.return_type
                v.cfc.free_var(e)
-               var iter = v.cfc.get_var
-               v.add_assignment(iter, prop.compile_call(v, [e]))
-               var prop2 = ittype.local_class.select_method(once "is_ok".to_symbol)
-               if prop2 == null then
-                       printl("No is_ok")
-                       return
-               end
-               var prop3 = ittype.local_class.select_method(once "item".to_symbol)
-               if prop3 == null then
-                       printl("No item")
-                       return
-               end
-               var prop4 = ittype.local_class.select_method(once "next".to_symbol)
-               if prop4 == null then
-                       printl("No next")
-                       return
-               end
+               var iter = v.cfc.get_var("For iterator")
+               v.add_assignment(iter, meth_iterator.compile_expr_call(v, [e]))
                v.add_instr("while (true) \{ /*for*/")
                v.indent
-               var ok = v.cfc.get_var
-               v.add_assignment(ok, prop2.compile_call(v, [iter]))
+               var ok = v.cfc.get_var("For 'is_ok' result")
+               v.add_assignment(ok, meth_is_ok.compile_expr_call(v, [iter]))
                v.add_instr("if (!UNTAG_Bool({ok})) break; /*for*/")
                v.cfc.free_var(ok)
-               var e = prop3.compile_call(v, [iter])
-               e = v.ensure_var(e)
+               var e = meth_item.compile_expr_call(v, [iter])
+               e = v.ensure_var(e, "For item")
                var cname = v.cfc.register_variable(variable)
                v.add_assignment(cname, e)
-               var par = parent
-               assert par isa AForExpr
-               var n_block = par.n_block
-               if n_block != null then
-                       v.compile_stmt(n_block)
-               end
+               v.compile_stmt(n_block)
                v.add_instr("{v.nmc.continue_label}: while(0);")
-               e = prop4.compile_call(v, [iter])
-               assert e == null
+               meth_next.compile_stmt_call(v, [iter])
                v.unindent
                v.add_instr("}")
                v.add_instr("{v.nmc.break_label}: while(0);")
@@ -1083,7 +1195,7 @@ redef class AVarReassignExpr
        do
                var e1 = v.cfc.varname(variable)
                var e2 = v.compile_expr(n_value)
-               var e3 = assign_method.compile_call(v, [e1, e2])
+               var e3 = assign_method.compile_expr_call(v, [e1, e2])
                v.add_assignment(v.cfc.varname(variable), "{e3} /*{variable.name}*/")
        end
 end
@@ -1098,7 +1210,7 @@ end
 redef class AOrExpr
        redef meth compile_expr(v)
        do
-               var e = v.ensure_var(v.compile_expr(n_expr))
+               var e = v.ensure_var(v.compile_expr(n_expr), "Left 'or' operand")
                v.add_instr("if (!UNTAG_Bool({e})) \{ /* or */")
                v.cfc.free_var(e)
                v.indent
@@ -1113,7 +1225,7 @@ end
 redef class AAndExpr
        redef meth compile_expr(v)
        do
-               var e = v.ensure_var(v.compile_expr(n_expr))
+               var e = v.ensure_var(v.compile_expr(n_expr), "Left 'and' operand")
                v.add_instr("if (UNTAG_Bool({e})) \{ /* and */")
                v.cfc.free_var(e)
                v.indent
@@ -1145,7 +1257,7 @@ redef class AIsaExpr
        redef meth compile_expr(v)
        do
                var e = v.compile_expr(n_expr)
-               return n_type.stype.compile_cast(v, e)
+               return n_type.stype.compile_cast(v, e, n_expr.stype)
        end
 end
 
@@ -1153,7 +1265,16 @@ redef class AAsCastExpr
        redef meth compile_expr(v)
        do
                var e = v.compile_expr(n_expr)
-               n_type.stype.compile_type_check(v, e, self)
+               n_type.stype.compile_type_check(v, e, self, n_expr.stype)
+               return e
+       end
+end
+
+redef class AAsNotnullExpr
+       redef meth compile_expr(v)
+       do
+               var e = v.compile_expr(n_expr)
+               n_expr.stype.compile_notnull_check(v, e, self)
                return e
        end
 end
@@ -1196,9 +1317,20 @@ end
 redef class AStringFormExpr
        redef meth compile_expr(v)
        do
-               var prop = stype.local_class.select_method(once "with_native".to_symbol)
                compute_string_info
-               return prop.compile_constructor_call(v, stype , ["BOX_NativeString(\"{_cstring}\")", "TAG_Int({_cstring_length})"])
+               var i = v.new_number
+               var cvar = v.cfc.get_var("Once String constant")
+               v.add_decl("static val_t once_value_{i} = NIT_NULL; /* Once value for string {cvar}*/")
+               v.add_instr("if (once_value_{i} != NIT_NULL) {cvar} = once_value_{i};")
+               v.add_instr("else \{")
+               v.indent
+               v.cfc.free_var(cvar)
+               var e = meth_with_native.compile_constructor_call(v, stype , ["BOX_NativeString(\"{_cstring}\")", "TAG_Int({_cstring_length})"])
+               v.add_assignment(cvar, e)
+               v.add_instr("once_value_{i} = {cvar};")
+               v.unindent
+               v.add_instr("}")
+               return cvar
        end
 
        # The raw string value
@@ -1215,7 +1347,7 @@ redef class AStringFormExpr
        do
                var len = 0
                var str = string_text
-               var res = new String
+               var res = new Buffer
                var i = 0
                while i < str.length do
                        var c = str[i]
@@ -1231,7 +1363,7 @@ redef class AStringFormExpr
                        res.add(c)
                        i = i + 1
                end
-               _cstring = res
+               _cstring = res.to_s
                _cstring_length = len
        end
 end
@@ -1252,21 +1384,20 @@ end
 redef class ASuperstringExpr
        redef meth compile_expr(v)
        do
-               var prop = stype.local_class.select_method(once "init".to_symbol)
-               var recv = prop.compile_constructor_call(v, stype, new Array[String]) 
-
-               var prop2 = stype.local_class.select_method(once "append".to_symbol)
+               var array = meth_with_capacity.compile_constructor_call(v, atype, ["TAG_Int({n_exprs.length})"])
+               array = v.ensure_var(array, "Array (for super-string)")
 
-               var prop3 = stype.local_class.select_method(once "to_s".to_symbol)
                for ne in n_exprs do
-                       var e = v.ensure_var(v.compile_expr(ne))
+                       var e = v.ensure_var(v.compile_expr(ne), "super-string element")
                        if ne.stype != stype then
-                               v.add_assignment(e, prop3.compile_call(v, [e]))
+                               v.cfc.free_var(e)
+                               e = meth_to_s.compile_expr_call(v, [e])
                        end
-                       prop2.compile_call(v, [recv, e])
+                       v.cfc.free_var(e)
+                       meth_add.compile_stmt_call(v, [array, e])
                end
 
-               return recv
+               return meth_to_s.compile_expr_call(v, [array])
        end
 end
 
@@ -1280,13 +1411,12 @@ end
 redef class AArrayExpr
        redef meth compile_expr(v)
        do
-               var prop = stype.local_class.select_method(once "with_capacity".to_symbol)
-               var recv = prop.compile_constructor_call(v, stype, ["TAG_Int({n_exprs.length})"])
+               var recv = meth_with_capacity.compile_constructor_call(v, stype, ["TAG_Int({n_exprs.length})"])
+               recv = v.ensure_var(recv, "Literal array")
 
-               var prop2 = stype.local_class.select_method(once "add".to_symbol)
                for ne in n_exprs do
                        var e = v.compile_expr(ne)
-                       prop2.compile_call(v, [recv, e])
+                       meth_add.compile_stmt_call(v, [recv, e])
                end
                return recv
        end
@@ -1295,31 +1425,30 @@ end
 redef class ARangeExpr
        redef meth compile_expr(v)
        do
-               var prop = stype.local_class.select_method(propname)
                var e = v.compile_expr(n_expr)
                var e2 = v.compile_expr(n_expr2)
-               return prop.compile_constructor_call(v, stype, [e, e2])
+               return meth_init.compile_constructor_call(v, stype, [e, e2])
        end
-       # The constructor that must be used for the range
-       protected meth propname: Symbol is abstract
-end
-
-redef class ACrangeExpr
-       redef meth propname do return once "init".to_symbol
-end
-redef class AOrangeExpr
-       redef meth propname do return once "without_last".to_symbol
 end
 
 redef class ASuperExpr
        redef meth compile_stmt(v)
        do
-               var e = compile_expr(v)
-               if e != null then v.add_instr("{e};")
+               var e = intern_compile_call(v)
+               if e != null then
+                       v.add_instr(e + ";")
+               end
        end
 
        redef meth compile_expr(v)
        do
+               var e = intern_compile_call(v)
+               assert e != null
+               return e
+       end
+
+       private meth intern_compile_call(v: CompilerVisitor): String
+       do
                var arity = v.nmc.method_params.length - 1
                if init_in_superclass != null then
                        arity = init_in_superclass.signature.arity
@@ -1337,7 +1466,7 @@ redef class ASuperExpr
                end
                #return "{prop.cname}({args.join(", ")}) /*super {prop.local_class}::{prop.name}*/"
                if init_in_superclass != null then
-                       return init_in_superclass.compile_call(v, args)
+                       return init_in_superclass.intern_compile_call(v, args)
                else
                        if prop.global.is_init then args.add("init_table")
                        return prop.compile_super_call(v, args)
@@ -1349,7 +1478,7 @@ redef class AAttrExpr
        redef meth compile_expr(v)
        do
                var e = v.compile_expr(n_expr)
-               return prop.compile_access(v, e)
+               return prop.compile_read_access(v, n_id, e)
        end
 end
 
@@ -1358,87 +1487,44 @@ redef class AAttrAssignExpr
        do
                var e = v.compile_expr(n_expr)
                var e2 = v.compile_expr(n_value)
-               v.add_assignment(prop.compile_access(v, e), e2)
+               prop.compile_write_access(v, n_id, e, e2)
        end
 end
 redef class AAttrReassignExpr
        redef meth compile_stmt(v)
        do
                var e1 = v.compile_expr(n_expr)
-               var e2 = prop.compile_access(v, e1)
+               var e2 = prop.compile_read_access(v, n_id, e1)
                var e3 = v.compile_expr(n_value)
-               var e4 = assign_method.compile_call(v, [e2, e3])
-               v.add_assignment(e2, e4)
+               var e4 = assign_method.compile_expr_call(v, [e2, e3])
+               prop.compile_write_access(v, n_id, e1, e4)
+       end
+end
+
+redef class AAbsAbsSendExpr
+       # Compile each argument and add them to the array
+       meth compile_arguments_in(v: CompilerVisitor, cargs: Array[String])
+       do
+               for a in arguments do
+                       cargs.add(v.compile_expr(a))
+               end
        end
+
 end
 
 redef class ASendExpr
-       redef meth compile_expr(v)
+       private meth intern_compile_call(v: CompilerVisitor): String
        do
                var recv = v.compile_expr(n_expr)
                var cargs = new Array[String]
                cargs.add(recv)
-               for a in arguments do
-                       cargs.add(v.compile_expr(a))
-               end
+               compile_arguments_in(v, cargs)
 
                var e: String
                if prop_signature.closures.is_empty then
-                       e = prop.compile_call(v, cargs)
+                       e = prop.intern_compile_call(v, cargs)
                else
-                       var cd = closure_defs
-                       var arity = 0
-                       if cd != null then arity = cd.length
-                       var closcns = new Array[String]
-                       var ve: String = null
-
-                       # Prepare result value.
-                       # In case of procedure, the return value is still used to intercept breaks
-                       var old_bv = v.nmc.break_value
-                       ve = v.cfc.get_var
-                       v.nmc.break_value = ve
-
-                       # Compile closure to c function
-                       for i in [0..arity[ do
-                               var cn = cd[i].compile_closure(v, prop.closure_cname(i))
-                               closcns.add(cn)
-                               cargs.add(cn)
-                       end
-                       for i in [arity..prop_signature.closures.length[ do
-                               cargs.add("NULL")
-                       end
-
-                       v.nmc.break_value = old_bv
-
-                       # Call
-                       e = prop.compile_call(v, cargs)
-                       if e != null then 
-                               v.add_assignment(ve, e)
-                               e = ve
-                       end
-
-                       # Intercept returns and breaks
-                       for i in [0..arity[ do
-                               # A break or a return is intercepted
-                               v.add_instr("if ({closcns[i]}->has_broke != NULL) \{")
-                               v.indent
-                               # A passtrought break or a return is intercepted: go the the next closure
-                               v.add_instr("if ({closcns[i]}->has_broke != &({ve})) \{")
-                               v.indent
-                               if v.cfc.in_closure then v.add_instr("closctx->has_broke = {closcns[i]}->has_broke; closctx->broke_value = {closcns[i]}->broke_value;")
-                               v.add_instr("goto {v.nmc.return_label};")
-                               v.unindent
-                               # A direct break is interpected
-                               if e != null then
-                                       # overwrite the returned value in a function
-                                       v.add_instr("\} else {ve} = {closcns[i]}->broke_value;")
-                               else
-                                       # Do nothing in a procedure
-                                       v.add_instr("\}")
-                               end
-                               v.unindent
-                               v.add_instr("\}")
-                       end
+                       e = prop.compile_call_and_closures(v, cargs, closure_defs)
                end
 
                if prop.global.is_init then
@@ -1447,9 +1533,16 @@ redef class ASendExpr
                return e
        end
 
+       redef meth compile_expr(v)
+       do
+               var e = intern_compile_call(v)
+               assert e != null
+               return e
+       end
+
        redef meth compile_stmt(v)
        do
-               var e = compile_expr(v)
+               var e = intern_compile_call(v)
                if e != null then
                        v.add_instr(e + ";")
                end
@@ -1457,20 +1550,20 @@ redef class ASendExpr
 end
 
 redef class ASendReassignExpr
-       redef meth compile_expr(v)
+       redef meth compile_expr(v) do abort
+
+       redef meth compile_stmt(v)
        do
                var recv = v.compile_expr(n_expr)
                var cargs = new Array[String]
                cargs.add(recv)
-               for a in arguments do
-                       cargs.add(v.compile_expr(a))
-               end
+               compile_arguments_in(v, cargs)
 
-               var e2 = read_prop.compile_call(v, cargs)
+               var e2 = read_prop.compile_expr_call(v, cargs)
                var e3 = v.compile_expr(n_value)
-               var e4 = assign_method.compile_call(v, [e2, e3])
+               var e4 = assign_method.compile_expr_call(v, [e2, e3])
                cargs.add(e4)
-               return prop.compile_call(v, cargs)
+               prop.compile_stmt_call(v, cargs)
        end
 end
 
@@ -1478,11 +1571,11 @@ redef class ANewExpr
        redef meth compile_expr(v)
        do
                var cargs = new Array[String]
-               for a in arguments do
-                       cargs.add(v.compile_expr(a))
-               end
+               compile_arguments_in(v, cargs)
                return prop.compile_constructor_call(v, stype, cargs) 
        end
+
+       redef meth compile_stmt(v) do abort
 end
 
 redef class PClosureDef
@@ -1504,12 +1597,12 @@ redef class AClosureDef
                v.ctx = new CContext
                v.out_contexts.add(v.ctx)
 
-               var cfc_old = v.cfc.in_closure
-               v.cfc.in_closure = true
+               var cfc_old = v.cfc.closure
+               v.cfc.closure = v.nmc
 
                var old_rv = v.nmc.return_value
                var old_bv = v.nmc.break_value
-               if not cfc_old then
+               if cfc_old == null then
                        v.nmc.return_value = "closctx->{old_rv}"
                        v.nmc.break_value = "closctx->{old_bv}"
                end
@@ -1548,14 +1641,16 @@ redef class AClosureDef
                v.add_instr("}")
                v.ctx = ctx_old
 
-               v.cfc.in_closure = cfc_old
+               v.cfc.closure = cfc_old
                v.nmc.return_value = old_rv
                v.nmc.break_value = old_bv
 
                # Build closure
                var closcnv = "wbclos{v.new_number}"
-               v.add_decl("struct {closcn} {closcnv} = \{{cname}, NULL\};")
-               if cfc_old then 
+               v.add_decl("struct WBT_ {closcnv};")
+               v.add_instr("{closcnv}.fun = (fun_t){cname};")
+               v.add_instr("{closcnv}.has_broke = NULL;")
+               if cfc_old != null then 
                        v.add_instr("{closcnv}.variable = closctx->variable;")
                        v.add_instr("{closcnv}.closurevariable = closctx->closurevariable;")
                else
@@ -1569,7 +1664,7 @@ redef class AClosureDef
        protected meth decl_csignature(v: CompilerVisitor, args: Array[String], closcn: String): String
        do
                var params = new Array[String]
-               params.add("struct {closcn}* closctx")
+               params.add("struct WBT_ *closctx")
                for i in [0..closure.signature.arity[ do
                        var p = "val_t {args[i]}"
                        params.add(p)
@@ -1582,7 +1677,6 @@ redef class AClosureDef
                end
                var p = params.join(", ")
                var s = "{ret} {cname}({p})"
-               v.add_decl("struct {closcn};")
                v.add_decl("typedef {ret} (* {cname}_t)({p});")
                v.add_decl(s + ";")
                return s
@@ -1599,11 +1693,11 @@ redef class AClosureDef
                var old_cl = v.nmc.continue_label
                var old_bl = v.nmc.break_label
 
-               v.nmc.continue_value = v.cfc.get_var
+               v.nmc.continue_value = v.cfc.get_var("Continue value and escape marker")
                v.nmc.continue_label = "continue_label{v.new_number}"
                v.nmc.break_label = v.nmc.return_label
 
-               if n_expr != null then v.compile_stmt(n_expr)
+               v.compile_stmt(n_expr)
 
                v.add_instr("{v.nmc.continue_label}: while(false);")
 
@@ -1630,11 +1724,11 @@ redef class AClosureDecl
                var old_cl = v.nmc.continue_label
                var old_bl = v.nmc.break_label
 
-               v.nmc.continue_value = v.cfc.get_var
+               v.nmc.continue_value = v.cfc.get_var("Continue value and escape marker")
                v.nmc.continue_label = "continue_label{v.new_number}"
                v.nmc.break_label = v.nmc.return_label
 
-               if n_expr != null then v.compile_stmt(n_expr)
+               v.compile_stmt(n_expr)
 
                v.add_instr("{v.nmc.continue_label}: while(false);")
 
@@ -1650,12 +1744,12 @@ redef class AClosureDecl
 end
 
 redef class AClosureCallExpr
-       redef meth compile_expr(v)
+       meth intern_compile_call(v: CompilerVisitor): String
        do
                var cargs = new Array[String]
-               for a in arguments do cargs.add(v.compile_expr(a))
+               compile_arguments_in(v, cargs)
                var va: String = null
-               if variable.closure.signature.return_type != null then va = v.cfc.get_var
+               if variable.closure.signature.return_type != null then va = v.cfc.get_var("Closure call result value")
 
                if variable.closure.is_optional then
                        v.add_instr("if({v.cfc.varname(variable)}==NULL) \{")
@@ -1669,10 +1763,10 @@ redef class AClosureCallExpr
                        v.indent
                end
 
-               var ivar = "(({variable.ctypename})({v.cfc.varname(variable)}))"
+               var ivar = v.cfc.varname(variable)
                var cargs2 = [ivar]
                cargs2.append(cargs)
-               var s = "({ivar}->fun({cargs2.join(", ")})) /* Invoke closure {variable} */"
+               var s = "(({variable.ctypename})({ivar}->fun))({cargs2.join(", ")}) /* Invoke closure {variable} */"
                if va != null then
                        v.add_assignment(va, s)
                else
@@ -1683,7 +1777,7 @@ redef class AClosureCallExpr
                if n_closure_defs != null and n_closure_defs.length == 1 then do
                        n_closure_defs.first.do_compile_inside(v, null)
                end
-               if v.cfc.in_closure then v.add_instr("if ({ivar}->has_broke) \{ closctx->has_broke = {ivar}->has_broke; closctx->broke_value = {ivar}->broke_value;\}")
+               if v.cfc.closure == v.nmc then v.add_instr("if ({ivar}->has_broke) \{ closctx->has_broke = {ivar}->has_broke; closctx->broke_value = {ivar}->broke_value;\}")
                v.add_instr("goto {v.nmc.return_label};")
                v.unindent
                v.add_instr("\}")
@@ -1694,6 +1788,21 @@ redef class AClosureCallExpr
                end
                return va
        end
+
+       redef meth compile_expr(v)
+       do
+               var e = intern_compile_call(v)
+               assert e != null
+               return e
+       end
+
+       redef meth compile_stmt(v)
+       do
+               var e = intern_compile_call(v)
+               if e != null then
+                       v.add_instr(e + ";")
+               end
+       end
 end
 
 redef class AProxyExpr
@@ -1707,7 +1816,7 @@ redef class AOnceExpr
        redef meth compile_expr(v)
        do
                var i = v.new_number
-               var cvar = v.cfc.get_var
+               var cvar = v.cfc.get_var("Once expression result")
                v.add_decl("static val_t once_value_{i}; static int once_bool_{i}; /* Once value for {cvar}*/")
                v.add_instr("if (once_bool_{i}) {cvar} = once_value_{i};")
                v.add_instr("else \{")