2005-01-31 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mcs / mcs / expression.cs
old mode 100755 (executable)
new mode 100644 (file)
index 05bf988..7ea0a61
@@ -217,6 +217,10 @@ namespace Mono.CSharp {
                                e = new IntConstant (-((ShortConstant) expr).Value);
                        else if (expr is UShortConstant)
                                e = new IntConstant (-((UShortConstant) expr).Value);
+                       else if (expr is SByteConstant)
+                               e = new IntConstant (-((SByteConstant) expr).Value);
+                       else if (expr is ByteConstant)
+                               e = new IntConstant (-((ByteConstant) expr).Value);
                        return e;
                }
 
@@ -237,7 +241,7 @@ namespace Mono.CSharp {
                                
                        case Operator.UnaryNegation:
                                result = TryReduceNegative (e);
-                               return true;
+                               return result != null;
                                
                        case Operator.LogicalNot:
                                if (expr_type != TypeManager.bool_type) {
@@ -323,11 +327,22 @@ namespace Mono.CSharp {
 
                Expression ResolveOperator (EmitContext ec)
                {
-                       Type expr_type = Expr.Type;
+                       //
+                       // Step 1: Default operations on CLI native types.
+                       //
+
+                       // Attempt to use a constant folding operation.
+                       if (Expr is Constant){
+                               Expression result;
+                               
+                               if (Reduce (ec, (Constant) Expr, out result))
+                                       return result;
+                       }
 
                        //
-                       // Step 1: Perform Operator Overload location
+                       // Step 2: Perform Operator Overload location
                        //
+                       Type expr_type = Expr.Type;
                        Expression mg;
                        string op_name;
                        
@@ -353,18 +368,6 @@ namespace Mono.CSharp {
                        if (expr_type == null)
                                return null;
                        
-                       //
-                       // Step 2: Default operations on CLI native types.
-                       //
-
-                       // Attempt to use a constant folding operation.
-                       if (Expr is Constant){
-                               Expression result;
-                               
-                               if (Reduce (ec, (Constant) Expr, out result))
-                                       return result;
-                       }
-
                        switch (Oper){
                        case Operator.LogicalNot:
                                if (expr_type != TypeManager.bool_type) {
@@ -428,21 +431,34 @@ namespace Mono.CSharp {
                                }
 
                                IVariable variable = Expr as IVariable;
-                               if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
+                               bool is_fixed = variable != null && variable.VerifyFixed (false);
+
+                               if (!ec.InFixedInitializer && !is_fixed) {
                                        Error (212, "You can only take the address of an unfixed expression inside " +
                                               "of a fixed statement initializer");
                                        return null;
                                }
-                               
-                               if (ec.InFixedInitializer && ((variable != null) && variable.VerifyFixed (false))) {
+
+                               if (ec.InFixedInitializer && is_fixed) {
                                        Error (213, "You can not fix an already fixed expression");
                                        return null;
                                }
 
+                               LocalVariableReference lr = Expr as LocalVariableReference;
+                               if (lr != null){
+                                       if (lr.local_info.IsCaptured){
+                                               AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
+                                               return null;
+                                       }
+                                       lr.local_info.AddressTaken = true;
+                                       lr.local_info.Used = true;
+                               }
+
                                // According to the specs, a variable is considered definitely assigned if you take
                                // its address.
-                               if ((variable != null) && (variable.VariableInfo != null))
+                               if ((variable != null) && (variable.VariableInfo != null)){
                                        variable.VariableInfo.SetAssigned (ec);
+                               }
 
                                type = TypeManager.GetPointerType (Expr.Type);
                                return this;
@@ -645,7 +661,7 @@ namespace Mono.CSharp {
        // after semantic analysis (this is so we can take the address
        // of an indirection).
        //
-       public class Indirection : Expression, IMemoryLocation, IAssignMethod {
+       public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
                Expression expr;
                LocalTemporary temporary;
                bool prepared;
@@ -719,6 +735,21 @@ namespace Mono.CSharp {
                {
                        return "*(" + expr + ")";
                }
+
+               #region IVariable Members
+
+               public VariableInfo VariableInfo {
+                       get {
+                               return null;
+                       }
+               }
+
+               public bool VerifyFixed (bool is_expression)
+               {
+                       return true;
+               }
+
+               #endregion
        }
        
        /// <summary>
@@ -1031,10 +1062,10 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       ProbeType = ProbeType.ResolveAsTypeTerminal (ec, false);
-                       if (ProbeType == null)
+                       TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec, false);
+                       if (texpr == null)
                                return null;
-                       probe_type = ProbeType.Type;
+                       probe_type = texpr.ResolveType (ec);
 
                        CheckObsoleteAttribute (probe_type);
 
@@ -1772,7 +1803,7 @@ namespace Mono.CSharp {
                        if (target == null)
                                return null;
 
-                       type = target.Type;
+                       type = target.ResolveType (ec);
 
                        CheckObsoleteAttribute (type);
 
@@ -2236,8 +2267,8 @@ namespace Mono.CSharp {
                        // Special cases: string comapred to null
                        //
                        if (oper == Operator.Equality || oper == Operator.Inequality){
-                               if ((l == TypeManager.string_type && (right is NullLiteral)) ||
-                                   (r == TypeManager.string_type && (left is NullLiteral))){
+                               if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
+                                   (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
                                        Type = TypeManager.bool_type;
                                        
                                        return this;
@@ -2374,8 +2405,8 @@ namespace Mono.CSharp {
                                        //
                                        // Also, a standard conversion must exist from either one
                                        //
-                                       if (!(Convert.ImplicitStandardConversionExists (left, r) ||
-                                             Convert.ImplicitStandardConversionExists (right, l))){
+                                       if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
+                                             Convert.ImplicitStandardConversionExists (ec, right, l))){
                                                Error_OperatorCannotBeApplied ();
                                                return null;
                                        }
@@ -2407,15 +2438,17 @@ namespace Mono.CSharp {
                        //
                        if (oper == Operator.Addition || oper == Operator.Subtraction) {
                                if (l.IsSubclassOf (TypeManager.delegate_type)){
-                                       if ((right.eclass == ExprClass.MethodGroup) &&
-                                           (RootContext.Version != LanguageVersion.ISO_1)){
-                                               Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
-                                               if (tmp == null)
-                                                       return null;
-                                               right = tmp;
-                                               r = right.Type;
+                                       if (((right.eclass == ExprClass.MethodGroup) ||
+                                            (r == TypeManager.anonymous_method_type))){
+                                               if ((RootContext.Version != LanguageVersion.ISO_1)){
+                                                       Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
+                                                       if (tmp == null)
+                                                               return null;
+                                                       right = tmp;
+                                                       r = right.Type;
+                                               }
                                        }
-                               
+                                       
                                        if (r.IsSubclassOf (TypeManager.delegate_type)){
                                                MethodInfo method;
                                                ArrayList args = new ArrayList (2);
@@ -2672,16 +2705,27 @@ namespace Mono.CSharp {
                                }
                        } else
                                left = left.Resolve (ec);
-                       right = right.Resolve (ec);
 
-                       if (left == null || right == null)
+                       if (left == null)
+                               return null;
+
+                       Constant lc = left as Constant;
+                       if (lc != null && lc.Type == TypeManager.bool_type && 
+                               ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
+                                (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
+
+                               // TODO: make a sense to resolve unreachable expression as we do for statement
+                               Report.Warning (429, 4, loc, "Unreachable expression code detected");
+                               return left;
+                       }
+
+                       right = right.Resolve (ec);
+                       if (right == null)
                                return null;
 
                        eclass = ExprClass.Value;
 
                        Constant rc = right as Constant;
-                       Constant lc = left as Constant;
-
                        if (rc != null & lc != null){
                                Expression e = ConstantFold.BinaryFold (
                                        ec, oper, lc, rc, loc);
@@ -3072,7 +3116,11 @@ namespace Mono.CSharp {
        public class StringConcat : Expression {
                ArrayList operands;
                bool invalid = false;
-               
+               bool emit_conv_done = false;
+               //
+               // Are we also concating objects?
+               //
+               bool is_strings_only = true;
                
                public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
                {
@@ -3126,30 +3174,30 @@ namespace Mono.CSharp {
                {
                        MethodInfo concat_method = null;
                        
-                       //
-                       // Are we also concating objects?
-                       //
-                       bool is_strings_only = true;
-                       
                        //
                        // Do conversion to arguments; check for strings only
                        //
-                       for (int i = 0; i < operands.Count; i ++) {
-                               Expression e = (Expression) operands [i];
-                               is_strings_only &= e.Type == TypeManager.string_type;
-                       }
                        
-                       for (int i = 0; i < operands.Count; i ++) {
-                               Expression e = (Expression) operands [i];
+                       // This can get called multiple times, so we have to deal with that.
+                       if (!emit_conv_done) {
+                               emit_conv_done = true;
+                               for (int i = 0; i < operands.Count; i ++) {
+                                       Expression e = (Expression) operands [i];
+                                       is_strings_only &= e.Type == TypeManager.string_type;
+                               }
                                
-                               if (! is_strings_only && e.Type == TypeManager.string_type) {
-                                       // need to make sure this is an object, because the EmitParams
-                                       // method might look at the type of this expression, see it is a
-                                       // string and emit a string [] when we want an object [];
+                               for (int i = 0; i < operands.Count; i ++) {
+                                       Expression e = (Expression) operands [i];
                                        
-                                       e = Convert.ImplicitConversion (ec, e, TypeManager.object_type, loc);
+                                       if (! is_strings_only && e.Type == TypeManager.string_type) {
+                                               // need to make sure this is an object, because the EmitParams
+                                               // method might look at the type of this expression, see it is a
+                                               // string and emit a string [] when we want an object [];
+                                               
+                                               e = new EmptyCast (e, TypeManager.object_type);
+                                       }
+                                       operands [i] = new Argument (e, Argument.AType.Expression);
                                }
-                               operands [i] = new Argument (e, Argument.AType.Expression);
                        }
                        
                        //
@@ -3312,8 +3360,6 @@ namespace Mono.CSharp {
                        Label false_target = ig.DefineLabel ();
                        Label end_target = ig.DefineLabel ();
 
-                       ig.Emit (OpCodes.Nop);
-
                        left.Emit (ec);
                        left_temp.Store (ec);
 
@@ -3323,8 +3369,6 @@ namespace Mono.CSharp {
                        ig.MarkLabel (false_target);
                        op.Emit (ec);
                        ig.MarkLabel (end_target);
-
-                       ig.Emit (OpCodes.Nop);
                }
        }
 
@@ -3386,17 +3430,26 @@ namespace Mono.CSharp {
                                //
                                left.Emit (ec);
                                ig.Emit (OpCodes.Conv_I);
-                               right.Emit (ec);
-                               if (size != 1){
-                                       if (size == 0)
-                                               ig.Emit (OpCodes.Sizeof, element);
-                                       else 
-                                               IntLiteral.EmitInt (ig, size);
-                                       if (rtype == TypeManager.int64_type)
-                                               ig.Emit (OpCodes.Conv_I8);
-                                       else if (rtype == TypeManager.uint64_type)
-                                               ig.Emit (OpCodes.Conv_U8);
-                                       ig.Emit (OpCodes.Mul);
+
+                               Constant right_const = right as Constant;
+                               if (right_const != null && size != 0) {
+                                       Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size), right_const, loc);
+                                       if (ex == null)
+                                               return;
+                                       ex.Emit (ec);
+                               } else {
+                                       right.Emit (ec);
+                                       if (size != 1){
+                                               if (size == 0)
+                                                       ig.Emit (OpCodes.Sizeof, element);
+                                               else 
+                                                       IntLiteral.EmitInt (ig, size);
+                                               if (rtype == TypeManager.int64_type)
+                                                       ig.Emit (OpCodes.Conv_I8);
+                                               else if (rtype == TypeManager.uint64_type)
+                                                       ig.Emit (OpCodes.Conv_U8);
+                                               ig.Emit (OpCodes.Mul);
+                                       }
                                }
                                
                                if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
@@ -3463,9 +3516,6 @@ namespace Mono.CSharp {
                        if (trueExpr == null || falseExpr == null)
                                return null;
 
-                       if ((trueExpr is NullLiteral) && (falseExpr is NullLiteral))
-                               return trueExpr;
-
                        eclass = ExprClass.Value;
                        if (trueExpr.Type == falseExpr.Type)
                                type = trueExpr.Type;
@@ -3505,13 +3555,12 @@ namespace Mono.CSharp {
                                }
                        }
 
+                       // Dead code optimalization
                        if (expr is BoolConstant){
                                BoolConstant bc = (BoolConstant) expr;
 
-                               if (bc.Value)
-                                       return trueExpr;
-                               else
-                                       return falseExpr;
+                               Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
+                               return bc.Value ? trueExpr : falseExpr;
                        }
 
                        return this;
@@ -3539,8 +3588,10 @@ namespace Mono.CSharp {
        public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
                public readonly string Name;
                public readonly Block Block;
-               LocalInfo local_info;
+               public LocalInfo local_info;
                bool is_readonly;
+               bool prepared;
+               LocalTemporary temp;
                
                public LocalVariableReference (Block block, string name, Location l)
                {
@@ -3550,8 +3601,10 @@ namespace Mono.CSharp {
                        eclass = ExprClass.Variable;
                }
 
+               //
                // Setting `is_readonly' to false will allow you to create a writable
                // reference to a read-only variable.  This is used by foreach and using.
+               //
                public LocalVariableReference (Block block, string name, Location l,
                                               LocalInfo local_info, bool is_readonly)
                        : this (block, name, l)
@@ -3561,7 +3614,9 @@ namespace Mono.CSharp {
                }
 
                public VariableInfo VariableInfo {
-                       get { return local_info.VariableInfo; }
+                       get {
+                               return local_info.VariableInfo;
+                       }
                }
 
                public bool IsReadOnly {
@@ -3570,22 +3625,31 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected void DoResolveBase (EmitContext ec)
+               protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
                {
                        if (local_info == null) {
                                local_info = Block.GetLocalInfo (Name);
+
+                               // is out param
+                               if (lvalue_right_side == EmptyExpression.Null)
+                                       local_info.Used = true;
+
                                is_readonly = local_info.ReadOnly;
                        }
 
                        type = local_info.VariableType;
-#if false
-                       if (ec.InAnonymousMethod)
-                               Block.LiftVariable (local_info);
-#endif
-               }
 
-               protected Expression DoResolve (EmitContext ec, bool is_lvalue)
-               {
+                       VariableInfo variable_info = local_info.VariableInfo;
+                       if (lvalue_right_side != null){
+                               if (is_readonly){
+                                       Error (1604, "cannot assign to `" + Name + "' because it is readonly");
+                                       return null;
+                               }
+                               
+                               if (variable_info != null)
+                                       variable_info.SetAssigned (ec);
+                       }
+                       
                        Expression e = Block.GetConstantExpression (Name);
                        if (e != null) {
                                local_info.Used = true;
@@ -3593,50 +3657,41 @@ namespace Mono.CSharp {
                                return e.Resolve (ec);
                        }
 
-                       VariableInfo variable_info = local_info.VariableInfo; 
                        if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
                                return null;
 
-                       if (!is_lvalue)
+                       if (lvalue_right_side == null)
                                local_info.Used = true;
 
-                       if (local_info.LocalBuilder == null)
-                               return ec.RemapLocal (local_info);
-                       
+                       if (ec.CurrentAnonymousMethod != null){
+                               //
+                               // If we are referencing a variable from the external block
+                               // flag it for capturing
+                               //
+                               if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
+                                       if (local_info.AddressTaken){
+                                               AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
+                                               return null;
+                                       }
+                                       ec.CaptureVariable (local_info);
+                               }
+                       }
+
                        return this;
                }
                
                public override Expression DoResolve (EmitContext ec)
                {
-                       DoResolveBase (ec);
-
-                       return DoResolve (ec, false);
+                       return DoResolveBase (ec, null);
                }
 
                override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
                {
-                       DoResolveBase (ec);
-
-                       VariableInfo variable_info = local_info.VariableInfo; 
-                       if (variable_info != null)
-                               variable_info.SetAssigned (ec);
-
-                       Expression e = DoResolve (ec, right_side != EmptyExpression.Null);
-
-                       if (e == null)
-                               return null;
-
-                       if (is_readonly){
-                               Error (1604, "cannot assign to `" + Name + "' because it is readonly");
-                               return null;
-                       }
-
-                       CheckObsoleteAttribute (e.Type);
-
-                       if (local_info.LocalBuilder == null)
-                               return ec.RemapLocalLValue (local_info, right_side);
+                       Expression ret = DoResolveBase (ec, right_side);
+                       if (ret != null)
+                               CheckObsoleteAttribute (ret.Type);
                        
-                       return this;
+                       return ret;
                }
 
                public bool VerifyFixed (bool is_expression)
@@ -3648,29 +3703,86 @@ namespace Mono.CSharp {
                {
                        ILGenerator ig = ec.ig;
 
-                       ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
+                       if (local_info.FieldBuilder == null){
+                               //
+                               // A local variable on the local CLR stack
+                               //
+                               ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
+                       } else {
+                               //
+                               // A local variable captured by anonymous methods.
+                               //
+                               if (!prepared)
+                                       ec.EmitCapturedVariableInstance (local_info);
+                               
+                               ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
+                       }
                }
                
                public void Emit (EmitContext ec, bool leave_copy)
                {
                        Emit (ec);
-                       if (leave_copy)
+                       if (leave_copy){
                                ec.ig.Emit (OpCodes.Dup);
+                               if (local_info.FieldBuilder != null){
+                                       temp = new LocalTemporary (ec, Type);
+                                       temp.Store (ec);
+                               }
+                       }
                }
                
                public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
                {
-                       source.Emit (ec);
-                       if (leave_copy)
-                               ec.ig.Emit (OpCodes.Dup);
-                       ec.ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
+                       ILGenerator ig = ec.ig;
+                       prepared = prepare_for_load;
+
+                       if (local_info.FieldBuilder == null){
+                               //
+                               // A local variable on the local CLR stack
+                               //
+                               if (local_info.LocalBuilder == null)
+                                       throw new Exception ("This should not happen: both Field and Local are null");
+                               
+                               source.Emit (ec);
+                               if (leave_copy)
+                                       ec.ig.Emit (OpCodes.Dup);
+                               ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
+                       } else {
+                               //
+                               // A local variable captured by anonymous methods or itereators.
+                               //
+                               ec.EmitCapturedVariableInstance (local_info);
+
+                               if (prepare_for_load)
+                                       ig.Emit (OpCodes.Dup);
+                               source.Emit (ec);
+                               if (leave_copy){
+                                       ig.Emit (OpCodes.Dup);
+                                       temp = new LocalTemporary (ec, Type);
+                                       temp.Store (ec);
+                               }
+                               ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
+                               if (temp != null)
+                                       temp.Emit (ec);
+                       }
                }
                
                public void AddressOf (EmitContext ec, AddressOp mode)
                {
                        ILGenerator ig = ec.ig;
-                       
-                       ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
+
+                       if (local_info.FieldBuilder == null){
+                               //
+                               // A local variable on the local CLR stack
+                               //
+                               ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
+                       } else {
+                               //
+                               // A local variable captured by anonymous methods or iterators
+                               //
+                               ec.EmitCapturedVariableInstance (local_info);
+                               ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
+                       }
                }
 
                public override string ToString ()
@@ -3691,6 +3803,19 @@ namespace Mono.CSharp {
                VariableInfo vi;
                public Parameter.Modifier mod;
                public bool is_ref, is_out, prepared;
+
+               public bool IsOut {
+                       get {
+                               return is_out;
+                       }
+               }
+
+               public bool IsRef {
+                       get {
+                               return is_ref;
+                       }
+               }
+
                LocalTemporary temp;
                
                public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
@@ -3714,8 +3839,7 @@ namespace Mono.CSharp {
 
                public bool IsAssigned (EmitContext ec, Location loc)
                {
-                       if (!ec.DoFlowAnalysis || !is_out ||
-                           ec.CurrentBranching.IsAssigned (vi))
+                       if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
                                return true;
 
                        Report.Error (165, loc,
@@ -3725,8 +3849,7 @@ namespace Mono.CSharp {
 
                public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
                {
-                       if (!ec.DoFlowAnalysis || !is_out ||
-                           ec.CurrentBranching.IsFieldAssigned (vi, field_name))
+                       if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
                                return true;
 
                        Report.Error (170, loc,
@@ -3740,7 +3863,7 @@ namespace Mono.CSharp {
                                ec.CurrentBranching.SetAssigned (vi);
                }
 
-               public void SetFieldAssigned (EmitContext ec, string field_name)
+               public void SetFieldAssigned (EmitContext ec, string field_name)        
                {
                        if (is_out && ec.DoFlowAnalysis)
                                ec.CurrentBranching.SetFieldAssigned (vi, field_name);
@@ -3748,13 +3871,30 @@ namespace Mono.CSharp {
 
                protected void DoResolveBase (EmitContext ec)
                {
-                       type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
+                       type = pars.GetParameterInfo (ec, idx, out mod);
                        is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
                        is_out = (mod & Parameter.Modifier.OUT) != 0;
                        eclass = ExprClass.Variable;
 
                        if (is_out)
                                vi = block.ParameterMap [idx];
+
+                       if (ec.CurrentAnonymousMethod != null){
+                               if (is_ref){
+                                       Report.Error (1628, Location,
+                                                     "Can not reference a ref or out parameter in an anonymous method");
+                                       return;
+                               }
+                               
+                               //
+                               // If we are referencing the parameter from the external block
+                               // flag it for capturing
+                               //
+                               //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
+                               if (!block.IsLocalParameter (name)){
+                                       ec.CaptureParameter (name, type, idx);
+                               }
+                       }
                }
 
                //
@@ -3823,17 +3963,25 @@ namespace Mono.CSharp {
                                arg_idx++;
 
                        EmitLdArg (ig, arg_idx);
+
+                       //
+                       // FIXME: Review for anonymous methods
+                       //
                }
                
                public override void Emit (EmitContext ec)
                {
+                       if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
+                               ec.EmitParameter (name);
+                               return;
+                       }
+                       
                        Emit (ec, false);
                }
                
                public void Emit (EmitContext ec, bool leave_copy)
                {
                        ILGenerator ig = ec.ig;
-                       
                        int arg_idx = idx;
 
                        if (!ec.IsStatic)
@@ -3864,6 +4012,11 @@ namespace Mono.CSharp {
                
                public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
                {
+                       if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
+                               ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
+                               return;
+                       }
+
                        ILGenerator ig = ec.ig;
                        int arg_idx = idx;
                        
@@ -3900,6 +4053,11 @@ namespace Mono.CSharp {
 
                public void AddressOf (EmitContext ec, AddressOp mode)
                {
+                       if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
+                               ec.EmitAddressOfParameter (name);
+                               return;
+                       }
+                       
                        int arg_idx = idx;
 
                        if (!ec.IsStatic)
@@ -4029,8 +4187,9 @@ namespace Mono.CSharp {
 
                                        if (instance.GetType () != typeof (This)){
                                                if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
-                                                       Report.Error (197, loc,
-                                                                     "Can not pass a type that derives from MarshalByRefObject with out or ref");
+                                                       Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
+                                                       Report.Error (197, loc, "Cannot pass '{0}' as ref or out or take its address because it is a member of a marshal-by-reference class",
+                                                               fe.Name);
                                                        return false;
                                                }
                                        }
@@ -4075,14 +4234,21 @@ namespace Mono.CSharp {
                                if (Expr is ParameterReference){
                                        ParameterReference pr = (ParameterReference) Expr;
 
-                                       if (pr.is_ref)
+                                       if (pr.IsRef)
                                                pr.EmitLoad (ec);
                                        else {
                                                
                                                pr.AddressOf (ec, mode);
                                        }
                                } else {
-                                       ((IMemoryLocation)Expr).AddressOf (ec, mode);
+                                       if (Expr is IMemoryLocation)
+                                               ((IMemoryLocation) Expr).AddressOf (ec, mode);
+                                       else {
+                                               Report.Error (
+                                                       1510, Expr.Location,
+                                                       "An lvalue is required as an argument to out or ref");
+                                               return;
+                                       }
                                }
                        } else
                                Expr.Emit (ec);
@@ -4185,9 +4351,9 @@ namespace Mono.CSharp {
                                //   * There is no implicit conversion from type 'object' to other reference types
                                //  => Conversion of 'null' to a reference type is better than conversion to 'object'
                                //
-                               //  FIXME: This probably isn't necessary, since the type of a NullLiteral is 'System.Null'.
-                               //         I think it used to be 'object' and thus needed a special case to avoid the
-                               //         immediately following two checks.
+                               //  FIXME: This probably isn't necessary, since the type of a NullLiteral is the 
+                               //         null type. I think it used to be 'object' and thus needed a special 
+                               //         case to avoid the immediately following two checks.
                                //
                                if (!p.IsValueType && q == TypeManager.object_type)
                                        return p;
@@ -4299,8 +4465,8 @@ namespace Mono.CSharp {
                        for (int j = 0; j < argument_count; ++j) {
                                Argument a = (Argument) args [j];
 
-                               Type ct = candidate_pd.ParameterType (j);
-                               Type bt = best_pd.ParameterType (j);
+                               Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
+                               Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
 
                                if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
                                        if (candidate_params)
@@ -4474,10 +4640,10 @@ namespace Mono.CSharp {
 
                                Argument a = (Argument) arguments [i];
 
-                               Parameter.Modifier a_mod = a.GetParameterModifier () &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
+                               Parameter.Modifier a_mod = a.GetParameterModifier () & 
+                                       (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
                                Parameter.Modifier p_mod = pd.ParameterModifier (i) &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
+                                       (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
 
                                if (a_mod == p_mod) {
 
@@ -4546,9 +4712,9 @@ namespace Mono.CSharp {
                                Argument a = (Argument) arguments [i];
 
                                Parameter.Modifier a_mod = a.GetParameterModifier () &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
+                                       unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
                                Parameter.Modifier p_mod = pd.ParameterModifier (i) &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
+                                       unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
 
 
                                if (a_mod == p_mod ||
@@ -4911,10 +5077,17 @@ namespace Mono.CSharp {
                                                a.Expr = conv;
                                }
 
+                               if (parameter_type.IsPointer){
+                                       if (!ec.InUnsafe){
+                                               UnsafeError (loc);
+                                               return false;
+                                       }
+                               }
+                               
                                Parameter.Modifier a_mod = a.GetParameterModifier () &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
+                                       unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
                                Parameter.Modifier p_mod = pd.ParameterModifier (j) &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
+                                       unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
                                
                                if (a_mod != p_mod &&
                                    pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
@@ -5027,6 +5200,9 @@ namespace Mono.CSharp {
                                }
                        }
 
+                       if (mg.InstanceExpression != null)
+                               mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
+
                        eclass = ExprClass.Value;
                        return this;
                }
@@ -5571,11 +5747,11 @@ namespace Mono.CSharp {
                                return this;
                        }
                        
-                       RequestedType = RequestedType.ResolveAsTypeTerminal (ec, false);
-                       if (RequestedType == null)
+                       TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
+                       if (texpr == null)
                                return null;
 
-                       type = RequestedType.Type;
+                       type = texpr.ResolveType (ec);
                        
                        CheckObsoleteAttribute (type);
 
@@ -5584,7 +5760,7 @@ namespace Mono.CSharp {
                        if (IsDelegate){
                                RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
                                if (RequestedType != null)
-                                       if (!(RequestedType is NewDelegate))
+                                       if (!(RequestedType is DelegateCreation))
                                                throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
                                return RequestedType;
                        }
@@ -5634,11 +5810,16 @@ namespace Mono.CSharp {
                                }
 
                                method = Invocation.OverloadResolve (
-                                       ec, (MethodGroupExpr) ml, Arguments, false, loc);
+                                       ec, (MethodGroupExpr) ml, Arguments, true, loc);
                                
                        }
 
-                       if (method == null) { 
+                       if (method == null) {
+                               if (almostMatchedMembers.Count != 0) {
+                                       MemberLookupFailed (ec, type, type, ".ctor", null, loc);
+                                       return null;
+                               }
+
                                 if (!is_struct || Arguments.Count > 0) {
                                        Error (1501, String.Format (
                                            "New invocation: Can not find a constructor in `{0}' for this argument list",
@@ -6060,12 +6241,13 @@ namespace Mono.CSharp {
                        //
                        // Lookup the type
                        //
-                       Expression array_type_expr;
+                       TypeExpr array_type_expr;
                        array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
-                       type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
-
-                       if (type == null)
+                       array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
+                       if (array_type_expr == null)
                                return false;
+
+                       type = array_type_expr.ResolveType (ec);
                        
                        if (!type.IsArray) {
                                Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
@@ -6773,11 +6955,11 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       QueriedType = QueriedType.ResolveAsTypeTerminal (ec, false);
-                       if (QueriedType == null)
+                       TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
+                       if (texpr == null)
                                return null;
 
-                       typearg = QueriedType.Type;
+                       typearg = texpr.ResolveType (ec);
 
                        if (typearg == TypeManager.void_type) {
                                Error (673, "System.Void cannot be used from C# - " +
@@ -6829,7 +7011,7 @@ namespace Mono.CSharp {
        ///   Implements the sizeof expression
        /// </summary>
        public class SizeOf : Expression {
-               public readonly Expression QueriedType;
+               public Expression QueriedType;
                Type type_queried;
                
                public SizeOf (Expression queried_type, Location l)
@@ -6846,11 +7028,13 @@ namespace Mono.CSharp {
                                        "(consider using System.Runtime.InteropServices.Marshal.SizeOf");
                                return null;
                        }
-                               
-                       type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
-                       if (type_queried == null)
+
+                       TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
+                       if (texpr == null)
                                return null;
 
+                       type_queried = texpr.ResolveType (ec);
+
                        CheckObsoleteAttribute (type_queried);
 
                        if (!TypeManager.IsUnmanagedType (type_queried)){
@@ -6908,9 +7092,11 @@ namespace Mono.CSharp {
                        if (sn == null || left == null || left.Type.Name != sn.Name)
                                return false;
 
-                       return RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc) != null;
+                       return ec.DeclSpace.LookupType (sn.Name, true, loc) != null;
                }
                
+               // TODO: possible optimalization
+               // Cache resolved constant result in FieldBuilder <-> expresion map
                public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
                                                              Expression left, Location loc,
                                                              Expression left_original)
@@ -6936,7 +7122,10 @@ namespace Mono.CSharp {
                                FieldInfo fi = fe.FieldInfo;
                                Type decl_type = fi.DeclaringType;
 
-                               if (fi is FieldBuilder) {
+                               bool is_emitted = fi is FieldBuilder;
+                               Type t = fi.FieldType;
+
+                               if (is_emitted) {
                                        Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
                                        
                                        if (c != null) {
@@ -6946,16 +7135,29 @@ namespace Mono.CSharp {
 
                                                object real_value = ((Constant) c.Expr).GetValue ();
 
-                                               return Constantify (real_value, fi.FieldType);
+                                               Expression exp = Constantify (real_value, t);
+
+                                               if (left_is_explicit && !left_is_type && !IdenticalNameAndTypeName (ec, left_original, left, loc)) {
+                                                       Report.SymbolRelatedToPreviousError (c);
+                                                       error176 (loc, c.GetSignatureForError ());
+                                                       return null;
+                                               }
+                                       
+                                               return exp;
                                        }
                                }
 
+                               // IsInitOnly is because of MS compatibility, I don't know why but they emit decimal constant as InitOnly
+                               if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
+                                       object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
+                                       if (attrs.Length == 1)
+                                               return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
+                               }
+
                                if (fi.IsLiteral) {
-                                       Type t = fi.FieldType;
-                                       
                                        object o;
 
-                                       if (fi is FieldBuilder)
+                                       if (is_emitted)
                                                o = TypeManager.GetValue ((FieldBuilder) fi);
                                        else
                                                o = fi.GetValue (fi);
@@ -6992,7 +7194,7 @@ namespace Mono.CSharp {
                                        return exp;
                                }
 
-                               if (fi.FieldType.IsPointer && !ec.InUnsafe){
+                               if (t.IsPointer && !ec.InUnsafe){
                                        UnsafeError (loc);
                                        return null;
                                }
@@ -7117,12 +7319,12 @@ namespace Mono.CSharp {
                        if (expr == null)
                                return null;
 
-                       if (expr is SimpleName){
-                               SimpleName child_expr = (SimpleName) expr;
-
-                               Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
-
-                               return new_expr.Resolve (ec, flags);
+                       if (expr is Namespace) {
+                               Namespace ns = (Namespace) expr;
+                               FullNamedExpression retval = ns.Lookup (ec.DeclSpace, Identifier, loc);
+                               if (retval == null)
+                                       Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
+                               return retval;
                        }
                                        
                        //
@@ -7186,7 +7388,8 @@ namespace Mono.CSharp {
                                return null;
 
                        if (member_lookup is TypeExpr) {
-                               if (!(expr is TypeExpr) && !(expr is SimpleName)) {
+                               if (!(expr is TypeExpr) && 
+                                   !IdenticalNameAndTypeName (ec, original, expr, loc)) {
                                        Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
                                               member_lookup.Type + "' instead");
                                        return null;
@@ -7212,47 +7415,32 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       return DoResolve (ec, null, ResolveFlags.VariableOrValue |
-                                         ResolveFlags.SimpleName | ResolveFlags.Type);
+                       return DoResolve (ec, null, ResolveFlags.VariableOrValue | ResolveFlags.Type);
                }
 
                public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
                {
-                       return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
-                                         ResolveFlags.SimpleName | ResolveFlags.Type);
+                       return DoResolve (ec, right_side, ResolveFlags.VariableOrValue | ResolveFlags.Type);
                }
 
-               public override Expression ResolveAsTypeStep (EmitContext ec)
+               public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
                {
-                       string fname = null;
-                       MemberAccess full_expr = this;
-                       while (full_expr != null) {
-                               if (fname != null)
-                                       fname = String.Concat (full_expr.Identifier, ".", fname);
-                               else
-                                       fname = full_expr.Identifier;
-
-                               if (full_expr.Expr is SimpleName) {
-                                       string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
-                                       Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
-                                       if (fully_qualified != null)
-                                               return new TypeExpression (fully_qualified, loc);
-                               }
-
-                               full_expr = full_expr.Expr as MemberAccess;
-                       }
+                       return ResolveNamespaceOrType (ec, false);
+               }
 
-                       Expression new_expr = expr.ResolveAsTypeStep (ec);
+               public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
+               {
+                       FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec);
 
                        if (new_expr == null)
                                return null;
 
-                       if (new_expr is SimpleName){
-                               SimpleName child_expr = (SimpleName) new_expr;
-                               
-                               new_expr = new SimpleName (child_expr.Name, Identifier, loc);
-
-                               return new_expr.ResolveAsTypeStep (ec);
+                       if (new_expr is Namespace) {
+                               Namespace ns = (Namespace) new_expr;
+                               FullNamedExpression retval = ns.Lookup (ec.DeclSpace, Identifier, loc);
+                               if (!silent && retval == null)
+                                       Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
+                               return retval;
                        }
 
                        Type expr_type = new_expr.Type;
@@ -7263,17 +7451,21 @@ namespace Mono.CSharp {
                                return null;
                        }
                        
-                       Expression member_lookup;
-                       member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
-                       if (member_lookup == null)
+                       Expression member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
+                       if (!silent && member_lookup == null) {
+                               Report.Error (234, loc, "The type name `{0}' could not be found in type `{1}'", 
+                                             Identifier, new_expr.FullName);
                                return null;
+                       }
 
-                       if (member_lookup is TypeExpr){
-                               member_lookup.Resolve (ec, ResolveFlags.Type);
-                               return member_lookup;
+                       if (!(member_lookup is TypeExpr)) {
+                               Report.Error (118, loc, "'{0}.{1}' denotes a '{2}', where a type was expected",
+                                             new_expr.FullName, Identifier, member_lookup.ExprClassName ());
+                               return null;
                        } 
 
-                       return null;                    
+                       member_lookup = member_lookup.Resolve (ec, ResolveFlags.Type);
+                       return (member_lookup as TypeExpr);
                }
 
                public override void Emit (EmitContext ec)
@@ -7917,10 +8109,9 @@ namespace Mono.CSharp {
                        if (!lookup_type.IsInterface)
                                return ix;
 
-                       TypeExpr [] ifaces = TypeManager.GetInterfaces (lookup_type);
+                       Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
                        if (ifaces != null) {
-                               foreach (TypeExpr iface in ifaces) {
-                                       Type itype = iface.Type;
+                               foreach (Type itype in ifaces) {
                                        MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
                                        if (mi != null){
                                                if (ix == null)
@@ -8040,6 +8231,8 @@ namespace Mono.CSharp {
                                UnsafeError (loc);
                                return null;
                        }
+
+                       instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
                        
                        eclass = ExprClass.IndexerAccess;
                        return this;
@@ -8110,6 +8303,8 @@ namespace Mono.CSharp {
                                }
                        }
                        
+                       instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
+
                        eclass = ExprClass.IndexerAccess;
                        return this;
                }
@@ -8348,6 +8543,12 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
+               public Expression Source {
+                       get {
+                               return source;
+                       }
+               }
+                       
                public override Expression DoResolve (EmitContext ec)
                {
                        //
@@ -8389,10 +8590,12 @@ namespace Mono.CSharp {
 
                public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
                {
-                       Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
-                       if (ltype == null)
+                       TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
+                       if (lexpr == null)
                                return null;
 
+                       Type ltype = lexpr.ResolveType (ec);
+
                        if ((ltype == TypeManager.void_type) && (dim != "*")) {
                                Report.Error (1547, Location,
                                              "Keyword 'void' cannot be used in this context");
@@ -8412,22 +8615,22 @@ namespace Mono.CSharp {
                                //
                                // For now, fall back to the full lookup in that case.
                                //
-                               type = RootContext.LookupType (
-                                       ec.DeclSpace, cname, false, loc);
-
+                               FullNamedExpression e = ec.DeclSpace.LookupType (cname, false, loc);
+                               if (e is TypeExpr)
+                                       type = ((TypeExpr) e).ResolveType (ec);
                                if (type == null)
                                        return null;
                        }
 
-                       if (!ec.ResolvingTypeTree){
-                               //
-                               // If the above flag is set, this is being invoked from the ResolveType function.
-                               // Upper layers take care of the type validity in this context.
-                               //
                        if (!ec.InUnsafe && type.IsPointer){
                                UnsafeError (loc);
                                return null;
                        }
+
+                       if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
+                               type.GetElementType () == TypeManager.typed_reference_type)) {
+                               Report.Error (611, loc, "Array elements cannot be of type '{0}'", TypeManager.CSharpName (type.GetElementType ()));
+                               return null;
                        }
                        
                        eclass = ExprClass.Type;
@@ -8439,6 +8642,12 @@ namespace Mono.CSharp {
                                return left + dim;
                        }
                }
+
+               public override string FullName {
+                       get {
+                               return type.FullName;
+                       }
+               }
        }
 
        //
@@ -8550,11 +8759,12 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       otype = ec.DeclSpace.ResolveType (t, false, loc);
-
-                       if (otype == null)
+                       TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
+                       if (texpr == null)
                                return null;
 
+                       otype = texpr.ResolveType (ec);
+
                        if (!TypeManager.VerifyUnManaged (otype, loc))
                                return null;