//
// expression.cs: Expression representation for the IL tree.
//
// Author:
// Miguel de Icaza (miguel@ximian.com)
//
// (C) 2001, 2002, 2003 Ximian, Inc.
// (C) 2003, 2004 Novell, Inc.
//
#define USE_OLD
namespace Mono.CSharp {
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
///
/// This is just a helper class, it is generated by Unary, UnaryMutator
/// when an overloaded method has been found. It just emits the code for a
/// static call.
///
public class StaticCallExpr : ExpressionStatement {
ArrayList args;
MethodInfo mi;
public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
{
mi = m;
args = a;
type = m.ReturnType;
eclass = ExprClass.Value;
loc = l;
}
public override Expression DoResolve (EmitContext ec)
{
//
// We are born fully resolved
//
return this;
}
public override void Emit (EmitContext ec)
{
if (args != null)
Invocation.EmitArguments (ec, mi, args, false, null);
ec.ig.Emit (OpCodes.Call, mi);
return;
}
static public StaticCallExpr MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
Expression e, Location loc)
{
ArrayList args;
MethodBase method;
args = new ArrayList (1);
Argument a = new Argument (e, Argument.AType.Expression);
// We need to resolve the arguments before sending them in !
if (!a.Resolve (ec, loc))
return null;
args.Add (a);
method = Invocation.OverloadResolve (
ec, (MethodGroupExpr) mg, args, false, loc);
if (method == null)
return null;
return new StaticCallExpr ((MethodInfo) method, args, loc);
}
public override void EmitStatement (EmitContext ec)
{
Emit (ec);
if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
ec.ig.Emit (OpCodes.Pop);
}
public MethodInfo Method {
get { return mi; }
}
}
public class ParenthesizedExpression : Expression
{
public Expression Expr;
public ParenthesizedExpression (Expression expr, Location loc)
{
this.Expr = expr;
this.loc = loc;
}
public override Expression DoResolve (EmitContext ec)
{
Expr = Expr.Resolve (ec);
return Expr;
}
public override void Emit (EmitContext ec)
{
throw new Exception ("Should not happen");
}
}
///
/// Unary expressions.
///
///
///
/// Unary implements unary expressions. It derives from
/// ExpressionStatement becuase the pre/post increment/decrement
/// operators can be used in a statement context.
///
public class Unary : Expression {
public enum Operator : byte {
UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
Indirection, AddressOf, TOP
}
public Operator Oper;
public Expression Expr;
public Unary (Operator op, Expression expr, Location loc)
{
this.Oper = op;
this.Expr = expr;
this.loc = loc;
}
///
/// Returns a stringified representation of the Operator
///
static public string OperName (Operator oper)
{
switch (oper){
case Operator.UnaryPlus:
return "+";
case Operator.UnaryNegation:
return "-";
case Operator.LogicalNot:
return "!";
case Operator.OnesComplement:
return "~";
case Operator.AddressOf:
return "&";
case Operator.Indirection:
return "*";
}
return oper.ToString ();
}
public static readonly string [] oper_names;
static Unary ()
{
oper_names = new string [(int)Operator.TOP];
oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
oper_names [(int) Operator.Indirection] = "op_Indirection";
oper_names [(int) Operator.AddressOf] = "op_AddressOf";
}
void Error23 (Type t)
{
Error (
23, "Operator " + OperName (Oper) +
" cannot be applied to operand of type `" +
TypeManager.CSharpName (t) + "'");
}
///
/// The result has been already resolved:
///
/// FIXME: a minus constant -128 sbyte cant be turned into a
/// constant byte.
///
static Expression TryReduceNegative (Constant expr)
{
Expression e = null;
if (expr is IntConstant)
e = new IntConstant (-((IntConstant) expr).Value);
else if (expr is UIntConstant){
uint value = ((UIntConstant) expr).Value;
if (value < 2147483649)
return new IntConstant (-(int)value);
else
e = new LongConstant (-value);
}
else if (expr is LongConstant)
e = new LongConstant (-((LongConstant) expr).Value);
else if (expr is ULongConstant){
ulong value = ((ULongConstant) expr).Value;
if (value < 9223372036854775809)
return new LongConstant(-(long)value);
}
else if (expr is FloatConstant)
e = new FloatConstant (-((FloatConstant) expr).Value);
else if (expr is DoubleConstant)
e = new DoubleConstant (-((DoubleConstant) expr).Value);
else if (expr is DecimalConstant)
e = new DecimalConstant (-((DecimalConstant) expr).Value);
else if (expr is ShortConstant)
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;
}
//
// This routine will attempt to simplify the unary expression when the
// argument is a constant. The result is returned in `result' and the
// function returns true or false depending on whether a reduction
// was performed or not
//
bool Reduce (EmitContext ec, Constant e, out Expression result)
{
Type expr_type = e.Type;
switch (Oper){
case Operator.UnaryPlus:
result = e;
return true;
case Operator.UnaryNegation:
result = TryReduceNegative (e);
return result != null;
case Operator.LogicalNot:
if (expr_type != TypeManager.bool_type) {
result = null;
Error23 (expr_type);
return false;
}
BoolConstant b = (BoolConstant) e;
result = new BoolConstant (!(b.Value));
return true;
case Operator.OnesComplement:
if (!((expr_type == TypeManager.int32_type) ||
(expr_type == TypeManager.uint32_type) ||
(expr_type == TypeManager.int64_type) ||
(expr_type == TypeManager.uint64_type) ||
(expr_type.IsSubclassOf (TypeManager.enum_type)))){
result = null;
if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
result = result.Resolve (ec);
} else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
result = result.Resolve (ec);
} else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
result = result.Resolve (ec);
} else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
result = result.Resolve (ec);
}
if (result == null || !(result is Constant)){
result = null;
Error23 (expr_type);
return false;
}
expr_type = result.Type;
e = (Constant) result;
}
if (e is EnumConstant){
EnumConstant enum_constant = (EnumConstant) e;
Expression reduced;
if (Reduce (ec, enum_constant.Child, out reduced)){
result = new EnumConstant ((Constant) reduced, enum_constant.Type);
return true;
} else {
result = null;
return false;
}
}
if (expr_type == TypeManager.int32_type){
result = new IntConstant (~ ((IntConstant) e).Value);
} else if (expr_type == TypeManager.uint32_type){
result = new UIntConstant (~ ((UIntConstant) e).Value);
} else if (expr_type == TypeManager.int64_type){
result = new LongConstant (~ ((LongConstant) e).Value);
} else if (expr_type == TypeManager.uint64_type){
result = new ULongConstant (~ ((ULongConstant) e).Value);
} else {
result = null;
Error23 (expr_type);
return false;
}
return true;
case Operator.AddressOf:
result = this;
return false;
case Operator.Indirection:
result = this;
return false;
}
throw new Exception ("Can not constant fold: " + Oper.ToString());
}
Expression ResolveOperator (EmitContext ec)
{
//
// 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 2: Perform Operator Overload location
//
Type expr_type = Expr.Type;
Expression mg;
string op_name;
op_name = oper_names [(int) Oper];
mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
if (mg != null) {
Expression e = StaticCallExpr.MakeSimpleCall (
ec, (MethodGroupExpr) mg, Expr, loc);
if (e == null){
Error23 (expr_type);
return null;
}
return e;
}
// Only perform numeric promotions on:
// +, -
if (expr_type == null)
return null;
switch (Oper){
case Operator.LogicalNot:
if (expr_type != TypeManager.bool_type) {
Expr = ResolveBoolean (ec, Expr, loc);
if (Expr == null){
Error23 (expr_type);
return null;
}
}
type = TypeManager.bool_type;
return this;
case Operator.OnesComplement:
if (!((expr_type == TypeManager.int32_type) ||
(expr_type == TypeManager.uint32_type) ||
(expr_type == TypeManager.int64_type) ||
(expr_type == TypeManager.uint64_type) ||
(expr_type.IsSubclassOf (TypeManager.enum_type)))){
Expression e;
e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
if (e != null){
type = TypeManager.int32_type;
return this;
}
e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
if (e != null){
type = TypeManager.uint32_type;
return this;
}
e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
if (e != null){
type = TypeManager.int64_type;
return this;
}
e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
if (e != null){
type = TypeManager.uint64_type;
return this;
}
Error23 (expr_type);
return null;
}
type = expr_type;
return this;
case Operator.AddressOf:
if (!ec.InUnsafe) {
UnsafeError (loc);
return null;
}
if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
return null;
}
IVariable variable = Expr as IVariable;
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 && 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))
variable.VariableInfo.SetAssigned (ec);
type = TypeManager.GetPointerType (Expr.Type);
return this;
case Operator.Indirection:
if (!ec.InUnsafe){
UnsafeError (loc);
return null;
}
if (!expr_type.IsPointer){
Error (193, "The * or -> operator can only be applied to pointers");
return null;
}
//
// We create an Indirection expression, because
// it can implement the IMemoryLocation.
//
return new Indirection (Expr, loc);
case Operator.UnaryPlus:
//
// A plus in front of something is just a no-op, so return the child.
//
return Expr;
case Operator.UnaryNegation:
//
// Deals with -literals
// int operator- (int x)
// long operator- (long x)
// float operator- (float f)
// double operator- (double d)
// decimal operator- (decimal d)
//
Expression expr = null;
//
// transform - - expr into expr
//
if (Expr is Unary){
Unary unary = (Unary) Expr;
if (unary.Oper == Operator.UnaryNegation)
return unary.Expr;
}
//
// perform numeric promotions to int,
// long, double.
//
//
// The following is inneficient, because we call
// ImplicitConversion too many times.
//
// It is also not clear if we should convert to Float
// or Double initially.
//
if (expr_type == TypeManager.uint32_type){
//
// FIXME: handle exception to this rule that
// permits the int value -2147483648 (-2^31) to
// bt wrote as a decimal interger literal
//
type = TypeManager.int64_type;
Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
return this;
}
if (expr_type == TypeManager.uint64_type){
//
// FIXME: Handle exception of `long value'
// -92233720368547758087 (-2^63) to be wrote as
// decimal integer literal.
//
Error23 (expr_type);
return null;
}
if (expr_type == TypeManager.float_type){
type = expr_type;
return this;
}
expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
if (expr != null){
Expr = expr;
type = expr.Type;
return this;
}
expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
if (expr != null){
Expr = expr;
type = expr.Type;
return this;
}
expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
if (expr != null){
Expr = expr;
type = expr.Type;
return this;
}
Error23 (expr_type);
return null;
}
Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
TypeManager.CSharpName (expr_type) + "'");
return null;
}
public override Expression DoResolve (EmitContext ec)
{
if (Oper == Operator.AddressOf) {
Expr = Expr.DoResolveLValue (ec, new EmptyExpression ());
if (Expr == null || Expr.eclass != ExprClass.Variable){
Error (211, "Cannot take the address of non-variables");
return null;
}
}
else
Expr = Expr.Resolve (ec);
if (Expr == null)
return null;
if (TypeManager.IsNullableType (Expr.Type))
return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
eclass = ExprClass.Value;
return ResolveOperator (ec);
}
public override Expression DoResolveLValue (EmitContext ec, Expression right)
{
if (Oper == Operator.Indirection)
return DoResolve (ec);
return null;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
switch (Oper) {
case Operator.UnaryPlus:
throw new Exception ("This should be caught by Resolve");
case Operator.UnaryNegation:
if (ec.CheckState) {
ig.Emit (OpCodes.Ldc_I4_0);
if (type == TypeManager.int64_type)
ig.Emit (OpCodes.Conv_U8);
Expr.Emit (ec);
ig.Emit (OpCodes.Sub_Ovf);
} else {
Expr.Emit (ec);
ig.Emit (OpCodes.Neg);
}
break;
case Operator.LogicalNot:
Expr.Emit (ec);
ig.Emit (OpCodes.Ldc_I4_0);
ig.Emit (OpCodes.Ceq);
break;
case Operator.OnesComplement:
Expr.Emit (ec);
ig.Emit (OpCodes.Not);
break;
case Operator.AddressOf:
((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
break;
default:
throw new Exception ("This should not happen: Operator = "
+ Oper.ToString ());
}
}
public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
{
if (Oper == Operator.LogicalNot)
Expr.EmitBranchable (ec, target, !onTrue);
else
base.EmitBranchable (ec, target, onTrue);
}
public override string ToString ()
{
return "Unary (" + Oper + ", " + Expr + ")";
}
}
//
// Unary operators are turned into Indirection expressions
// after semantic analysis (this is so we can take the address
// of an indirection).
//
public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
Expression expr;
LocalTemporary temporary;
bool prepared;
public Indirection (Expression expr, Location l)
{
this.expr = expr;
type = TypeManager.HasElementType (expr.Type) ? TypeManager.GetElementType (expr.Type) : expr.Type;
eclass = ExprClass.Variable;
loc = l;
}
void LoadExprValue (EmitContext ec)
{
}
public override void Emit (EmitContext ec)
{
if (!prepared)
expr.Emit (ec);
LoadFromPtr (ec.ig, Type);
}
public void Emit (EmitContext ec, bool leave_copy)
{
Emit (ec);
if (leave_copy) {
ec.ig.Emit (OpCodes.Dup);
temporary = new LocalTemporary (ec, expr.Type);
temporary.Store (ec);
}
}
public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
{
prepared = prepare_for_load;
expr.Emit (ec);
if (prepare_for_load)
ec.ig.Emit (OpCodes.Dup);
source.Emit (ec);
if (leave_copy) {
ec.ig.Emit (OpCodes.Dup);
temporary = new LocalTemporary (ec, expr.Type);
temporary.Store (ec);
}
StoreFromPtr (ec.ig, type);
if (temporary != null)
temporary.Emit (ec);
}
public void AddressOf (EmitContext ec, AddressOp Mode)
{
expr.Emit (ec);
}
public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
return DoResolve (ec);
}
public override Expression DoResolve (EmitContext ec)
{
//
// Born fully resolved
//
return this;
}
public override string ToString ()
{
return "*(" + expr + ")";
}
#region IVariable Members
public VariableInfo VariableInfo {
get {
return null;
}
}
public bool VerifyFixed (bool is_expression)
{
return true;
}
#endregion
}
///
/// Unary Mutator expressions (pre and post ++ and --)
///
///
///
/// UnaryMutator implements ++ and -- expressions. It derives from
/// ExpressionStatement becuase the pre/post increment/decrement
/// operators can be used in a statement context.
///
/// FIXME: Idea, we could split this up in two classes, one simpler
/// for the common case, and one with the extra fields for more complex
/// classes (indexers require temporary access; overloaded require method)
///
///
public class UnaryMutator : ExpressionStatement {
[Flags]
public enum Mode : byte {
IsIncrement = 0,
IsDecrement = 1,
IsPre = 0,
IsPost = 2,
PreIncrement = 0,
PreDecrement = IsDecrement,
PostIncrement = IsPost,
PostDecrement = IsPost | IsDecrement
}
Mode mode;
bool is_expr = false;
bool recurse = false;
Expression expr;
//
// This is expensive for the simplest case.
//
StaticCallExpr method;
public UnaryMutator (Mode m, Expression e, Location l)
{
mode = m;
loc = l;
expr = e;
}
static string OperName (Mode mode)
{
return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
"++" : "--";
}
void Error23 (Type t)
{
Error (
23, "Operator " + OperName (mode) +
" cannot be applied to operand of type `" +
TypeManager.CSharpName (t) + "'");
}
///
/// Returns whether an object of type `t' can be incremented
/// or decremented with add/sub (ie, basically whether we can
/// use pre-post incr-decr operations on it, but it is not a
/// System.Decimal, which we require operator overloading to catch)
///
static bool IsIncrementableNumber (Type t)
{
return (t == TypeManager.sbyte_type) ||
(t == TypeManager.byte_type) ||
(t == TypeManager.short_type) ||
(t == TypeManager.ushort_type) ||
(t == TypeManager.int32_type) ||
(t == TypeManager.uint32_type) ||
(t == TypeManager.int64_type) ||
(t == TypeManager.uint64_type) ||
(t == TypeManager.char_type) ||
(t.IsSubclassOf (TypeManager.enum_type)) ||
(t == TypeManager.float_type) ||
(t == TypeManager.double_type) ||
(t.IsPointer && t != TypeManager.void_ptr_type);
}
Expression ResolveOperator (EmitContext ec)
{
Type expr_type = expr.Type;
//
// Step 1: Perform Operator Overload location
//
Expression mg;
string op_name;
if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
op_name = "op_Increment";
else
op_name = "op_Decrement";
mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
if (mg != null) {
method = StaticCallExpr.MakeSimpleCall (
ec, (MethodGroupExpr) mg, expr, loc);
type = method.Type;
} else if (!IsIncrementableNumber (expr_type)) {
Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
TypeManager.CSharpName (expr_type) + "'");
return null;
}
//
// The operand of the prefix/postfix increment decrement operators
// should be an expression that is classified as a variable,
// a property access or an indexer access
//
type = expr_type;
if (expr.eclass == ExprClass.Variable){
LocalVariableReference var = expr as LocalVariableReference;
if ((var != null) && var.IsReadOnly) {
Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
return null;
}
} else if (expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess){
expr = expr.ResolveLValue (ec, this);
if (expr == null)
return null;
} else {
expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
return null;
}
return this;
}
public override Expression DoResolve (EmitContext ec)
{
expr = expr.Resolve (ec);
if (expr == null)
return null;
eclass = ExprClass.Value;
if (TypeManager.IsNullableType (expr.Type))
return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
return ResolveOperator (ec);
}
static int PtrTypeSize (Type t)
{
return GetTypeSize (TypeManager.GetElementType (t));
}
//
// Loads the proper "1" into the stack based on the type, then it emits the
// opcode for the operation requested
//
void LoadOneAndEmitOp (EmitContext ec, Type t)
{
//
// Measure if getting the typecode and using that is more/less efficient
// that comparing types. t.GetTypeCode() is an internal call.
//
ILGenerator ig = ec.ig;
if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
LongConstant.EmitLong (ig, 1);
else if (t == TypeManager.double_type)
ig.Emit (OpCodes.Ldc_R8, 1.0);
else if (t == TypeManager.float_type)
ig.Emit (OpCodes.Ldc_R4, 1.0F);
else if (t.IsPointer){
int n = PtrTypeSize (t);
if (n == 0)
ig.Emit (OpCodes.Sizeof, t);
else
IntConstant.EmitInt (ig, n);
} else
ig.Emit (OpCodes.Ldc_I4_1);
//
// Now emit the operation
//
if (ec.CheckState){
if (t == TypeManager.int32_type ||
t == TypeManager.int64_type){
if ((mode & Mode.IsDecrement) != 0)
ig.Emit (OpCodes.Sub_Ovf);
else
ig.Emit (OpCodes.Add_Ovf);
} else if (t == TypeManager.uint32_type ||
t == TypeManager.uint64_type){
if ((mode & Mode.IsDecrement) != 0)
ig.Emit (OpCodes.Sub_Ovf_Un);
else
ig.Emit (OpCodes.Add_Ovf_Un);
} else {
if ((mode & Mode.IsDecrement) != 0)
ig.Emit (OpCodes.Sub_Ovf);
else
ig.Emit (OpCodes.Add_Ovf);
}
} else {
if ((mode & Mode.IsDecrement) != 0)
ig.Emit (OpCodes.Sub);
else
ig.Emit (OpCodes.Add);
}
if (t == TypeManager.sbyte_type){
if (ec.CheckState)
ig.Emit (OpCodes.Conv_Ovf_I1);
else
ig.Emit (OpCodes.Conv_I1);
} else if (t == TypeManager.byte_type){
if (ec.CheckState)
ig.Emit (OpCodes.Conv_Ovf_U1);
else
ig.Emit (OpCodes.Conv_U1);
} else if (t == TypeManager.short_type){
if (ec.CheckState)
ig.Emit (OpCodes.Conv_Ovf_I2);
else
ig.Emit (OpCodes.Conv_I2);
} else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
if (ec.CheckState)
ig.Emit (OpCodes.Conv_Ovf_U2);
else
ig.Emit (OpCodes.Conv_U2);
}
}
void EmitCode (EmitContext ec, bool is_expr)
{
recurse = true;
this.is_expr = is_expr;
((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
}
public override void Emit (EmitContext ec)
{
//
// We use recurse to allow ourselfs to be the source
// of an assignment. This little hack prevents us from
// having to allocate another expression
//
if (recurse) {
((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
if (method == null)
LoadOneAndEmitOp (ec, expr.Type);
else
ec.ig.Emit (OpCodes.Call, method.Method);
recurse = false;
return;
}
EmitCode (ec, true);
}
public override void EmitStatement (EmitContext ec)
{
EmitCode (ec, false);
}
}
///
/// Base class for the `Is' and `As' classes.
///
///
///
/// FIXME: Split this in two, and we get to save the `Operator' Oper
/// size.
///
public abstract class Probe : Expression {
public Expression ProbeType;
protected Expression expr;
protected Type probe_type;
public Probe (Expression expr, Expression probe_type, Location l)
{
ProbeType = probe_type;
loc = l;
this.expr = expr;
}
public Expression Expr {
get {
return expr;
}
}
public override Expression DoResolve (EmitContext ec)
{
TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec);
if (texpr == null)
return null;
probe_type = texpr.Type;
CheckObsoleteAttribute (probe_type);
expr = expr.Resolve (ec);
if (expr == null)
return null;
if (expr.Type.IsPointer) {
Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
return null;
}
return this;
}
}
///
/// Implementation of the `is' operator.
///
public class Is : Probe {
public Is (Expression expr, Expression probe_type, Location l)
: base (expr, probe_type, l)
{
}
enum Action {
AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
}
Action action;
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
expr.Emit (ec);
switch (action){
case Action.AlwaysFalse:
ig.Emit (OpCodes.Pop);
IntConstant.EmitInt (ig, 0);
return;
case Action.AlwaysTrue:
ig.Emit (OpCodes.Pop);
IntConstant.EmitInt (ig, 1);
return;
case Action.LeaveOnStack:
// the `e != null' rule.
ig.Emit (OpCodes.Ldnull);
ig.Emit (OpCodes.Ceq);
ig.Emit (OpCodes.Ldc_I4_0);
ig.Emit (OpCodes.Ceq);
return;
case Action.Probe:
ig.Emit (OpCodes.Isinst, probe_type);
ig.Emit (OpCodes.Ldnull);
ig.Emit (OpCodes.Cgt_Un);
return;
}
throw new Exception ("never reached");
}
public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
{
ILGenerator ig = ec.ig;
switch (action){
case Action.AlwaysFalse:
if (! onTrue)
ig.Emit (OpCodes.Br, target);
return;
case Action.AlwaysTrue:
if (onTrue)
ig.Emit (OpCodes.Br, target);
return;
case Action.LeaveOnStack:
// the `e != null' rule.
expr.Emit (ec);
ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
return;
case Action.Probe:
expr.Emit (ec);
ig.Emit (OpCodes.Isinst, probe_type);
ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
return;
}
throw new Exception ("never reached");
}
public override Expression DoResolve (EmitContext ec)
{
Expression e = base.DoResolve (ec);
if ((e == null) || (expr == null))
return null;
Type etype = expr.Type;
bool warning_always_matches = false;
bool warning_never_matches = false;
type = TypeManager.bool_type;
eclass = ExprClass.Value;
//
// First case, if at compile time, there is an implicit conversion
// then e != null (objects) or true (value types)
//
e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
if (e != null){
expr = e;
if (etype.IsValueType)
action = Action.AlwaysTrue;
else
action = Action.LeaveOnStack;
warning_always_matches = true;
} else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
if (etype.IsGenericParameter)
expr = new BoxedCast (expr, etype);
//
// Second case: explicit reference convresion
//
if (expr is NullLiteral)
action = Action.AlwaysFalse;
else
action = Action.Probe;
} else {
action = Action.AlwaysFalse;
warning_never_matches = true;
}
if (warning_always_matches)
Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
else if (warning_never_matches){
if (!(probe_type.IsInterface || expr.Type.IsInterface))
Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
}
return this;
}
}
///
/// Implementation of the `as' operator.
///
public class As : Probe {
public As (Expression expr, Expression probe_type, Location l)
: base (expr, probe_type, l)
{
}
bool do_isinst = false;
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
expr.Emit (ec);
if (do_isinst)
ig.Emit (OpCodes.Isinst, probe_type);
}
static void Error_CannotConvertType (Type source, Type target, Location loc)
{
Report.Error (
39, loc, "as operator can not convert from `" +
TypeManager.CSharpName (source) + "' to `" +
TypeManager.CSharpName (target) + "'");
}
public override Expression DoResolve (EmitContext ec)
{
Expression e = base.DoResolve (ec);
if (e == null)
return null;
type = probe_type;
eclass = ExprClass.Value;
Type etype = expr.Type;
if (TypeManager.IsValueType (probe_type)){
Report.Error (77, loc, "The as operator should be used with a reference type only (" +
TypeManager.CSharpName (probe_type) + " is a value type)");
return null;
}
e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
if (e != null){
expr = e;
do_isinst = false;
return this;
}
if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
if (etype.IsGenericParameter)
expr = new BoxedCast (expr, etype);
do_isinst = true;
return this;
}
Error_CannotConvertType (etype, probe_type, loc);
return null;
}
}
///
/// This represents a typecast in the source language.
///
/// FIXME: Cast expressions have an unusual set of parsing
/// rules, we need to figure those out.
///
public class Cast : Expression {
Expression target_type;
Expression expr;
public Cast (Expression cast_type, Expression expr, Location loc)
{
this.target_type = cast_type;
this.expr = expr;
this.loc = loc;
}
public Expression TargetType {
get {
return target_type;
}
}
public Expression Expr {
get {
return expr;
}
set {
expr = value;
}
}
bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
{
if (!ec.ConstantCheckState)
return true;
if ((value < min) || (value > max)) {
Error (221, "Constant value `" + value + "' cannot be converted " +
"to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
"syntax to override)");
return false;
}
return true;
}
bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
{
if (!ec.ConstantCheckState)
return true;
if (value > max) {
Error (221, "Constant value `" + value + "' cannot be converted " +
"to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
"syntax to override)");
return false;
}
return true;
}
bool CheckUnsigned (EmitContext ec, long value, Type type)
{
if (!ec.ConstantCheckState)
return true;
if (value < 0) {
Error (221, "Constant value `" + value + "' cannot be converted " +
"to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
"syntax to override)");
return false;
}
return true;
}
///
/// Attempts to do a compile-time folding of a constant cast.
///
Expression TryReduce (EmitContext ec, Type target_type)
{
Expression real_expr = expr;
if (real_expr is EnumConstant)
real_expr = ((EnumConstant) real_expr).Child;
if (real_expr is ByteConstant){
byte v = ((ByteConstant) real_expr).Value;
if (target_type == TypeManager.sbyte_type) {
if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
return null;
return new SByteConstant ((sbyte) v);
}
if (target_type == TypeManager.short_type)
return new ShortConstant ((short) v);
if (target_type == TypeManager.ushort_type)
return new UShortConstant ((ushort) v);
if (target_type == TypeManager.int32_type)
return new IntConstant ((int) v);
if (target_type == TypeManager.uint32_type)
return new UIntConstant ((uint) v);
if (target_type == TypeManager.int64_type)
return new LongConstant ((long) v);
if (target_type == TypeManager.uint64_type)
return new ULongConstant ((ulong) v);
if (target_type == TypeManager.float_type)
return new FloatConstant ((float) v);
if (target_type == TypeManager.double_type)
return new DoubleConstant ((double) v);
if (target_type == TypeManager.char_type)
return new CharConstant ((char) v);
if (target_type == TypeManager.decimal_type)
return new DecimalConstant ((decimal) v);
}
if (real_expr is SByteConstant){
sbyte v = ((SByteConstant) real_expr).Value;
if (target_type == TypeManager.byte_type) {
if (!CheckUnsigned (ec, v, target_type))
return null;
return new ByteConstant ((byte) v);
}
if (target_type == TypeManager.short_type)
return new ShortConstant ((short) v);
if (target_type == TypeManager.ushort_type) {
if (!CheckUnsigned (ec, v, target_type))
return null;
return new UShortConstant ((ushort) v);
} if (target_type == TypeManager.int32_type)
return new IntConstant ((int) v);
if (target_type == TypeManager.uint32_type) {
if (!CheckUnsigned (ec, v, target_type))
return null;
return new UIntConstant ((uint) v);
} if (target_type == TypeManager.int64_type)
return new LongConstant ((long) v);
if (target_type == TypeManager.uint64_type) {
if (!CheckUnsigned (ec, v, target_type))
return null;
return new ULongConstant ((ulong) v);
}
if (target_type == TypeManager.float_type)
return new FloatConstant ((float) v);
if (target_type == TypeManager.double_type)
return new DoubleConstant ((double) v);
if (target_type == TypeManager.char_type) {
if (!CheckUnsigned (ec, v, target_type))
return null;
return new CharConstant ((char) v);
}
if (target_type == TypeManager.decimal_type)
return new DecimalConstant ((decimal) v);
}
if (real_expr is ShortConstant){
short v = ((ShortConstant) real_expr).Value;
if (target_type == TypeManager.byte_type) {
if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
return null;
return new ByteConstant ((byte) v);
}
if (target_type == TypeManager.sbyte_type) {
if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
return null;
return new SByteConstant ((sbyte) v);
}
if (target_type == TypeManager.ushort_type) {
if (!CheckUnsigned (ec, v, target_type))
return null;
return new UShortConstant ((ushort) v);
}
if (target_type == TypeManager.int32_type)
return new IntConstant ((int) v);
if (target_type == TypeManager.uint32_type) {
if (!CheckUnsigned (ec, v, target_type))
return null;
return new UIntConstant ((uint) v);
}
if (target_type == TypeManager.int64_type)
return new LongConstant ((long) v);
if (target_type == TypeManager.uint64_type) {
if (!CheckUnsigned (ec, v, target_type))
return null;
return new ULongConstant ((ulong) v);
}
if (target_type == TypeManager.float_type)
return new FloatConstant ((float) v);
if (target_type == TypeManager.double_type)
return new DoubleConstant ((double) v);
if (target_type == TypeManager.char_type) {
if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
return null;
return new CharConstant ((char) v);
}
if (target_type == TypeManager.decimal_type)
return new DecimalConstant ((decimal) v);
}
if (real_expr is UShortConstant){
ushort v = ((UShortConstant) real_expr).Value;
if (target_type == TypeManager.byte_type) {
if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
return null;
return new ByteConstant ((byte) v);
}
if (target_type == TypeManager.sbyte_type) {
if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
return null;
return new SByteConstant ((sbyte) v);
}
if (target_type == TypeManager.short_type) {
if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
return null;
return new ShortConstant ((short) v);
}
if (target_type == TypeManager.int32_type)
return new IntConstant ((int) v);
if (target_type == TypeManager.uint32_type)
return new UIntConstant ((uint) v);
if (target_type == TypeManager.int64_type)
return new LongConstant ((long) v);
if (target_type == TypeManager.uint64_type)
return new ULongConstant ((ulong) v);
if (target_type == TypeManager.float_type)
return new FloatConstant ((float) v);
if (target_type == TypeManager.double_type)
return new DoubleConstant ((double) v);
if (target_type == TypeManager.char_type) {
if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
return null;
return new CharConstant ((char) v);
}
if (target_type == TypeManager.decimal_type)
return new DecimalConstant ((decimal) v);
}
if (real_expr is IntConstant){
int v = ((IntConstant) real_expr).Value;
if (target_type == TypeManager.byte_type) {
if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
return null;
return new ByteConstant ((byte) v);
}
if (target_type == TypeManager.sbyte_type) {
if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
return null;
return new SByteConstant ((sbyte) v);
}
if (target_type == TypeManager.short_type) {
if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
return null;
return new ShortConstant ((short) v);
}
if (target_type == TypeManager.ushort_type) {
if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
return null;
return new UShortConstant ((ushort) v);
}
if (target_type == TypeManager.uint32_type) {
if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
return null;
return new UIntConstant ((uint) v);
}
if (target_type == TypeManager.int64_type)
return new LongConstant ((long) v);
if (target_type == TypeManager.uint64_type) {
if (!CheckUnsigned (ec, v, target_type))
return null;
return new ULongConstant ((ulong) v);
}
if (target_type == TypeManager.float_type)
return new FloatConstant ((float) v);
if (target_type == TypeManager.double_type)
return new DoubleConstant ((double) v);
if (target_type == TypeManager.char_type) {
if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
return null;
return new CharConstant ((char) v);
}
if (target_type == TypeManager.decimal_type)
return new DecimalConstant ((decimal) v);
}
if (real_expr is UIntConstant){
uint v = ((UIntConstant) real_expr).Value;
if (target_type == TypeManager.byte_type) {
if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
return null;
return new ByteConstant ((byte) v);
}
if (target_type == TypeManager.sbyte_type) {
if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
return null;
return new SByteConstant ((sbyte) v);
}
if (target_type == TypeManager.short_type) {
if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
return null;
return new ShortConstant ((short) v);
}
if (target_type == TypeManager.ushort_type) {
if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
return null;
return new UShortConstant ((ushort) v);
}
if (target_type == TypeManager.int32_type) {
if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
return null;
return new IntConstant ((int) v);
}
if (target_type == TypeManager.int64_type)
return new LongConstant ((long) v);
if (target_type == TypeManager.uint64_type)
return new ULongConstant ((ulong) v);
if (target_type == TypeManager.float_type)
return new FloatConstant ((float) v);
if (target_type == TypeManager.double_type)
return new DoubleConstant ((double) v);
if (target_type == TypeManager.char_type) {
if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
return null;
return new CharConstant ((char) v);
}
if (target_type == TypeManager.decimal_type)
return new DecimalConstant ((decimal) v);
}
if (real_expr is LongConstant){
long v = ((LongConstant) real_expr).Value;
if (target_type == TypeManager.byte_type) {
if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
return null;
return new ByteConstant ((byte) v);
}
if (target_type == TypeManager.sbyte_type) {
if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
return null;
return new SByteConstant ((sbyte) v);
}
if (target_type == TypeManager.short_type) {
if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
return null;
return new ShortConstant ((short) v);
}
if (target_type == TypeManager.ushort_type) {
if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
return null;
return new UShortConstant ((ushort) v);
}
if (target_type == TypeManager.int32_type) {
if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
return null;
return new IntConstant ((int) v);
}
if (target_type == TypeManager.uint32_type) {
if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
return null;
return new UIntConstant ((uint) v);
}
if (target_type == TypeManager.uint64_type) {
if (!CheckUnsigned (ec, v, target_type))
return null;
return new ULongConstant ((ulong) v);
}
if (target_type == TypeManager.float_type)
return new FloatConstant ((float) v);
if (target_type == TypeManager.double_type)
return new DoubleConstant ((double) v);
if (target_type == TypeManager.char_type) {
if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
return null;
return new CharConstant ((char) v);
}
if (target_type == TypeManager.decimal_type)
return new DecimalConstant ((decimal) v);
}
if (real_expr is ULongConstant){
ulong v = ((ULongConstant) real_expr).Value;
if (target_type == TypeManager.byte_type) {
if (!CheckRange (ec, v, target_type, Byte.MaxValue))
return null;
return new ByteConstant ((byte) v);
}
if (target_type == TypeManager.sbyte_type) {
if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
return null;
return new SByteConstant ((sbyte) v);
}
if (target_type == TypeManager.short_type) {
if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
return null;
return new ShortConstant ((short) v);
}
if (target_type == TypeManager.ushort_type) {
if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
return null;
return new UShortConstant ((ushort) v);
}
if (target_type == TypeManager.int32_type) {
if (!CheckRange (ec, v, target_type, Int32.MaxValue))
return null;
return new IntConstant ((int) v);
}
if (target_type == TypeManager.uint32_type) {
if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
return null;
return new UIntConstant ((uint) v);
}
if (target_type == TypeManager.int64_type) {
if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
return null;
return new LongConstant ((long) v);
}
if (target_type == TypeManager.float_type)
return new FloatConstant ((float) v);
if (target_type == TypeManager.double_type)
return new DoubleConstant ((double) v);
if (target_type == TypeManager.char_type) {
if (!CheckRange (ec, v, target_type, Char.MaxValue))
return null;
return new CharConstant ((char) v);
}
if (target_type == TypeManager.decimal_type)
return new DecimalConstant ((decimal) v);
}
if (real_expr is FloatConstant){
float v = ((FloatConstant) real_expr).Value;
if (target_type == TypeManager.byte_type)
return new ByteConstant ((byte) v);
if (target_type == TypeManager.sbyte_type)
return new SByteConstant ((sbyte) v);
if (target_type == TypeManager.short_type)
return new ShortConstant ((short) v);
if (target_type == TypeManager.ushort_type)
return new UShortConstant ((ushort) v);
if (target_type == TypeManager.int32_type)
return new IntConstant ((int) v);
if (target_type == TypeManager.uint32_type)
return new UIntConstant ((uint) v);
if (target_type == TypeManager.int64_type)
return new LongConstant ((long) v);
if (target_type == TypeManager.uint64_type)
return new ULongConstant ((ulong) v);
if (target_type == TypeManager.double_type)
return new DoubleConstant ((double) v);
if (target_type == TypeManager.char_type)
return new CharConstant ((char) v);
if (target_type == TypeManager.decimal_type)
return new DecimalConstant ((decimal) v);
}
if (real_expr is DoubleConstant){
double v = ((DoubleConstant) real_expr).Value;
if (target_type == TypeManager.byte_type){
return new ByteConstant ((byte) v);
} if (target_type == TypeManager.sbyte_type)
return new SByteConstant ((sbyte) v);
if (target_type == TypeManager.short_type)
return new ShortConstant ((short) v);
if (target_type == TypeManager.ushort_type)
return new UShortConstant ((ushort) v);
if (target_type == TypeManager.int32_type)
return new IntConstant ((int) v);
if (target_type == TypeManager.uint32_type)
return new UIntConstant ((uint) v);
if (target_type == TypeManager.int64_type)
return new LongConstant ((long) v);
if (target_type == TypeManager.uint64_type)
return new ULongConstant ((ulong) v);
if (target_type == TypeManager.float_type)
return new FloatConstant ((float) v);
if (target_type == TypeManager.char_type)
return new CharConstant ((char) v);
if (target_type == TypeManager.decimal_type)
return new DecimalConstant ((decimal) v);
}
if (real_expr is CharConstant){
char v = ((CharConstant) real_expr).Value;
if (target_type == TypeManager.byte_type) {
if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
return null;
return new ByteConstant ((byte) v);
}
if (target_type == TypeManager.sbyte_type) {
if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
return null;
return new SByteConstant ((sbyte) v);
}
if (target_type == TypeManager.short_type) {
if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
return null;
return new ShortConstant ((short) v);
}
if (target_type == TypeManager.int32_type)
return new IntConstant ((int) v);
if (target_type == TypeManager.uint32_type)
return new UIntConstant ((uint) v);
if (target_type == TypeManager.int64_type)
return new LongConstant ((long) v);
if (target_type == TypeManager.uint64_type)
return new ULongConstant ((ulong) v);
if (target_type == TypeManager.float_type)
return new FloatConstant ((float) v);
if (target_type == TypeManager.double_type)
return new DoubleConstant ((double) v);
if (target_type == TypeManager.char_type) {
if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
return null;
return new CharConstant ((char) v);
}
if (target_type == TypeManager.decimal_type)
return new DecimalConstant ((decimal) v);
}
return null;
}
public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
expr = expr.DoResolveLValue (ec, right_side);
if (expr == null)
return null;
return ResolveRest (ec);
}
public override Expression DoResolve (EmitContext ec)
{
expr = expr.Resolve (ec);
if (expr == null)
return null;
return ResolveRest (ec);
}
Expression ResolveRest (EmitContext ec)
{
TypeExpr target = target_type.ResolveAsTypeTerminal (ec);
if (target == null)
return null;
type = target.Type;
CheckObsoleteAttribute (type);
if (type.IsAbstract && type.IsSealed) {
Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
return null;
}
eclass = ExprClass.Value;
if (expr is Constant){
Expression e = TryReduce (ec, type);
if (e != null)
return e;
}
if (type.IsPointer && !ec.InUnsafe) {
UnsafeError (loc);
return null;
}
expr = Convert.ExplicitConversion (ec, expr, type, loc);
return expr;
}
public override void Emit (EmitContext ec)
{
//
// This one will never happen
//
throw new Exception ("Should not happen");
}
}
///
/// Binary operators
///
public class Binary : Expression {
public enum Operator : byte {
Multiply, Division, Modulus,
Addition, Subtraction,
LeftShift, RightShift,
LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
Equality, Inequality,
BitwiseAnd,
ExclusiveOr,
BitwiseOr,
LogicalAnd,
LogicalOr,
TOP
}
Operator oper;
Expression left, right;
// This must be kept in sync with Operator!!!
public static readonly string [] oper_names;
static Binary ()
{
oper_names = new string [(int) Operator.TOP];
oper_names [(int) Operator.Multiply] = "op_Multiply";
oper_names [(int) Operator.Division] = "op_Division";
oper_names [(int) Operator.Modulus] = "op_Modulus";
oper_names [(int) Operator.Addition] = "op_Addition";
oper_names [(int) Operator.Subtraction] = "op_Subtraction";
oper_names [(int) Operator.LeftShift] = "op_LeftShift";
oper_names [(int) Operator.RightShift] = "op_RightShift";
oper_names [(int) Operator.LessThan] = "op_LessThan";
oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
oper_names [(int) Operator.Equality] = "op_Equality";
oper_names [(int) Operator.Inequality] = "op_Inequality";
oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
}
public Binary (Operator oper, Expression left, Expression right, Location loc)
{
this.oper = oper;
this.left = left;
this.right = right;
this.loc = loc;
}
public Operator Oper {
get {
return oper;
}
set {
oper = value;
}
}
public Expression Left {
get {
return left;
}
set {
left = value;
}
}
public Expression Right {
get {
return right;
}
set {
right = value;
}
}
///
/// Returns a stringified representation of the Operator
///
static string OperName (Operator oper)
{
switch (oper){
case Operator.Multiply:
return "*";
case Operator.Division:
return "/";
case Operator.Modulus:
return "%";
case Operator.Addition:
return "+";
case Operator.Subtraction:
return "-";
case Operator.LeftShift:
return "<<";
case Operator.RightShift:
return ">>";
case Operator.LessThan:
return "<";
case Operator.GreaterThan:
return ">";
case Operator.LessThanOrEqual:
return "<=";
case Operator.GreaterThanOrEqual:
return ">=";
case Operator.Equality:
return "==";
case Operator.Inequality:
return "!=";
case Operator.BitwiseAnd:
return "&";
case Operator.BitwiseOr:
return "|";
case Operator.ExclusiveOr:
return "^";
case Operator.LogicalOr:
return "||";
case Operator.LogicalAnd:
return "&&";
}
return oper.ToString ();
}
public override string ToString ()
{
return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
right.ToString () + ")";
}
Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
{
if (expr.Type == target_type)
return expr;
return Convert.ImplicitConversion (ec, expr, target_type, loc);
}
public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
{
Report.Error (
34, loc, "Operator `" + OperName (oper)
+ "' is ambiguous on operands of type `"
+ TypeManager.CSharpName (l) + "' "
+ "and `" + TypeManager.CSharpName (r)
+ "'");
}
bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
{
if ((l == t) || (r == t))
return true;
if (!check_user_conversions)
return false;
if (Convert.ImplicitUserConversionExists (ec, l, t))
return true;
else if (Convert.ImplicitUserConversionExists (ec, r, t))
return true;
else
return false;
}
//
// Note that handling the case l == Decimal || r == Decimal
// is taken care of by the Step 1 Operator Overload resolution.
//
// If `check_user_conv' is true, we also check whether a user-defined conversion
// exists. Note that we only need to do this if both arguments are of a user-defined
// type, otherwise ConvertImplict() already finds the user-defined conversion for us,
// so we don't explicitly check for performance reasons.
//
bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
{
if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
//
// If either operand is of type double, the other operand is
// conveted to type double.
//
if (r != TypeManager.double_type)
right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
if (l != TypeManager.double_type)
left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
type = TypeManager.double_type;
} else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
//
// if either operand is of type float, the other operand is
// converted to type float.
//
if (r != TypeManager.double_type)
right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
if (l != TypeManager.double_type)
left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
type = TypeManager.float_type;
} else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
Expression e;
Type other;
//
// If either operand is of type ulong, the other operand is
// converted to type ulong. or an error ocurrs if the other
// operand is of type sbyte, short, int or long
//
if (l == TypeManager.uint64_type){
if (r != TypeManager.uint64_type){
if (right is IntConstant){
IntConstant ic = (IntConstant) right;
e = Convert.TryImplicitIntConversion (l, ic);
if (e != null)
right = e;
} else if (right is LongConstant){
long ll = ((LongConstant) right).Value;
if (ll >= 0)
right = new ULongConstant ((ulong) ll);
} else {
e = Convert.ImplicitNumericConversion (ec, right, l, loc);
if (e != null)
right = e;
}
}
other = right.Type;
} else {
if (left is IntConstant){
e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
if (e != null)
left = e;
} else if (left is LongConstant){
long ll = ((LongConstant) left).Value;
if (ll > 0)
left = new ULongConstant ((ulong) ll);
} else {
e = Convert.ImplicitNumericConversion (ec, left, r, loc);
if (e != null)
left = e;
}
other = left.Type;
}
if ((other == TypeManager.sbyte_type) ||
(other == TypeManager.short_type) ||
(other == TypeManager.int32_type) ||
(other == TypeManager.int64_type))
Error_OperatorAmbiguous (loc, oper, l, r);
else {
left = ForceConversion (ec, left, TypeManager.uint64_type);
right = ForceConversion (ec, right, TypeManager.uint64_type);
}
type = TypeManager.uint64_type;
} else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
//
// If either operand is of type long, the other operand is converted
// to type long.
//
if (l != TypeManager.int64_type)
left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
if (r != TypeManager.int64_type)
right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
type = TypeManager.int64_type;
} else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
//
// If either operand is of type uint, and the other
// operand is of type sbyte, short or int, othe operands are
// converted to type long (unless we have an int constant).
//
Type other = null;
if (l == TypeManager.uint32_type){
if (right is IntConstant){
IntConstant ic = (IntConstant) right;
int val = ic.Value;
if (val >= 0){
right = new UIntConstant ((uint) val);
type = l;
return true;
}
}
other = r;
} else if (r == TypeManager.uint32_type){
if (left is IntConstant){
IntConstant ic = (IntConstant) left;
int val = ic.Value;
if (val >= 0){
left = new UIntConstant ((uint) val);
type = r;
return true;
}
}
other = l;
}
if ((other == TypeManager.sbyte_type) ||
(other == TypeManager.short_type) ||
(other == TypeManager.int32_type)){
left = ForceConversion (ec, left, TypeManager.int64_type);
right = ForceConversion (ec, right, TypeManager.int64_type);
type = TypeManager.int64_type;
} else {
//
// if either operand is of type uint, the other
// operand is converd to type uint
//
left = ForceConversion (ec, left, TypeManager.uint32_type);
right = ForceConversion (ec, right, TypeManager.uint32_type);
type = TypeManager.uint32_type;
}
} else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
if (l != TypeManager.decimal_type)
left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
if (r != TypeManager.decimal_type)
right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
type = TypeManager.decimal_type;
} else {
left = ForceConversion (ec, left, TypeManager.int32_type);
right = ForceConversion (ec, right, TypeManager.int32_type);
type = TypeManager.int32_type;
}
return (left != null) && (right != null);
}
static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
{
Report.Error (19, loc,
"Operator " + name + " cannot be applied to operands of type `" +
TypeManager.CSharpName (l) + "' and `" +
TypeManager.CSharpName (r) + "'");
}
void Error_OperatorCannotBeApplied ()
{
Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
}
static bool is_unsigned (Type t)
{
return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
t == TypeManager.short_type || t == TypeManager.byte_type);
}
static bool is_user_defined (Type t)
{
if (t.IsSubclassOf (TypeManager.value_type) &&
(!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
return true;
else
return false;
}
Expression Make32or64 (EmitContext ec, Expression e)
{
Type t= e.Type;
if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
t == TypeManager.int64_type || t == TypeManager.uint64_type)
return e;
Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
if (ee != null)
return ee;
ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
if (ee != null)
return ee;
ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
if (ee != null)
return ee;
ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
if (ee != null)
return ee;
return null;
}
Expression CheckShiftArguments (EmitContext ec)
{
Expression e;
e = ForceConversion (ec, right, TypeManager.int32_type);
if (e == null){
Error_OperatorCannotBeApplied ();
return null;
}
right = e;
if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
left = e;
type = e.Type;
if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
right = right.DoResolve (ec);
} else {
right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
right = right.DoResolve (ec);
}
return this;
}
Error_OperatorCannotBeApplied ();
return null;
}
Expression ResolveOperator (EmitContext ec)
{
Type l = left.Type;
Type r = right.Type;
//
// Special cases: string or type parameter comapred to null
//
if (oper == Operator.Equality || oper == Operator.Inequality){
if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
(!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
Type = TypeManager.bool_type;
return this;
}
if (l.IsGenericParameter && (right is NullLiteral)) {
if (l.BaseType == TypeManager.value_type) {
Error_OperatorCannotBeApplied ();
return null;
}
left = new BoxedCast (left);
Type = TypeManager.bool_type;
return this;
}
if (r.IsGenericParameter && (left is NullLiteral)) {
if (r.BaseType == TypeManager.value_type) {
Error_OperatorCannotBeApplied ();
return null;
}
right = new BoxedCast (right);
Type = TypeManager.bool_type;
return this;
}
// IntPtr equality
if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
Type = TypeManager.bool_type;
return this;
}
}
//
// Do not perform operator overload resolution when both sides are
// built-in types
//
if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
//
// Step 1: Perform Operator Overload location
//
Expression left_expr, right_expr;
string op = oper_names [(int) oper];
MethodGroupExpr union;
left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
if (r != l){
right_expr = MemberLookup (
ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
} else
union = (MethodGroupExpr) left_expr;
if (union != null) {
ArrayList args = new ArrayList (2);
args.Add (new Argument (left, Argument.AType.Expression));
args.Add (new Argument (right, Argument.AType.Expression));
MethodBase method = Invocation.OverloadResolve (
ec, union, args, true, Location.Null);
if (method != null) {
MethodInfo mi = (MethodInfo) method;
return new BinaryMethod (mi.ReturnType, method, args);
}
}
}
//
// Step 0: String concatenation (because overloading will get this wrong)
//
if (oper == Operator.Addition){
//
// If any of the arguments is a string, cast to string
//
// Simple constant folding
if (left is StringConstant && right is StringConstant)
return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
if (l == TypeManager.string_type || r == TypeManager.string_type) {
if (r == TypeManager.void_type || l == TypeManager.void_type) {
Error_OperatorCannotBeApplied ();
return null;
}
// try to fold it in on the left
if (left is StringConcat) {
//
// We have to test here for not-null, since we can be doubly-resolved
// take care of not appending twice
//
if (type == null){
type = TypeManager.string_type;
((StringConcat) left).Append (ec, right);
return left.Resolve (ec);
} else {
return left;
}
}
// Otherwise, start a new concat expression
return new StringConcat (ec, loc, left, right).Resolve (ec);
}
//
// Transform a + ( - b) into a - b
//
if (right is Unary){
Unary right_unary = (Unary) right;
if (right_unary.Oper == Unary.Operator.UnaryNegation){
oper = Operator.Subtraction;
right = right_unary.Expr;
r = right.Type;
}
}
}
if (oper == Operator.Equality || oper == Operator.Inequality){
if (l == TypeManager.bool_type || r == TypeManager.bool_type){
if (r != TypeManager.bool_type || l != TypeManager.bool_type){
Error_OperatorCannotBeApplied ();
return null;
}
type = TypeManager.bool_type;
return this;
}
bool left_is_null = left is NullLiteral;
bool right_is_null = right is NullLiteral;
if (left_is_null || right_is_null) {
if (oper == Operator.Equality)
return new BoolLiteral (left_is_null == right_is_null);
else
return new BoolLiteral (left_is_null != right_is_null);
}
//
// operator != (object a, object b)
// operator == (object a, object b)
//
// For this to be used, both arguments have to be reference-types.
// Read the rationale on the spec (14.9.6)
//
// Also, if at compile time we know that the classes do not inherit
// one from the other, then we catch the error there.
//
if (!(l.IsValueType || r.IsValueType)){
type = TypeManager.bool_type;
if (l == r)
return this;
if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
return this;
//
// Also, a standard conversion must exist from either one
//
if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
Convert.ImplicitStandardConversionExists (ec, right, l))){
Error_OperatorCannotBeApplied ();
return null;
}
//
// We are going to have to convert to an object to compare
//
if (l != TypeManager.object_type)
left = new EmptyCast (left, TypeManager.object_type);
if (r != TypeManager.object_type)
right = new EmptyCast (right, TypeManager.object_type);
//
// FIXME: CSC here catches errors cs254 and cs252
//
return this;
}
//
// One of them is a valuetype, but the other one is not.
//
if (!l.IsValueType || !r.IsValueType) {
Error_OperatorCannotBeApplied ();
return null;
}
}
// Only perform numeric promotions on:
// +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
//
if (oper == Operator.Addition || oper == Operator.Subtraction) {
if (TypeManager.IsDelegateType (l)){
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 (TypeManager.IsDelegateType (r)){
MethodInfo method;
ArrayList args = new ArrayList (2);
args = new ArrayList (2);
args.Add (new Argument (left, Argument.AType.Expression));
args.Add (new Argument (right, Argument.AType.Expression));
if (oper == Operator.Addition)
method = TypeManager.delegate_combine_delegate_delegate;
else
method = TypeManager.delegate_remove_delegate_delegate;
if (!TypeManager.IsEqual (l, r)) {
Error_OperatorCannotBeApplied ();
return null;
}
return new BinaryDelegate (l, method, args);
}
}
//
// Pointer arithmetic:
//
// T* operator + (T* x, int y);
// T* operator + (T* x, uint y);
// T* operator + (T* x, long y);
// T* operator + (T* x, ulong y);
//
// T* operator + (int y, T* x);
// T* operator + (uint y, T *x);
// T* operator + (long y, T *x);
// T* operator + (ulong y, T *x);
//
// T* operator - (T* x, int y);
// T* operator - (T* x, uint y);
// T* operator - (T* x, long y);
// T* operator - (T* x, ulong y);
//
// long operator - (T* x, T *y)
//
if (l.IsPointer){
if (r.IsPointer && oper == Operator.Subtraction){
if (r == l)
return new PointerArithmetic (
false, left, right, TypeManager.int64_type,
loc).Resolve (ec);
} else {
Expression t = Make32or64 (ec, right);
if (t != null)
return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
}
} else if (r.IsPointer && oper == Operator.Addition){
Expression t = Make32or64 (ec, left);
if (t != null)
return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
}
}
//
// Enumeration operators
//
bool lie = TypeManager.IsEnumType (l);
bool rie = TypeManager.IsEnumType (r);
if (lie || rie){
Expression temp;
// U operator - (E e, E f)
if (lie && rie){
if (oper == Operator.Subtraction){
if (l == r){
type = TypeManager.EnumToUnderlying (l);
return this;
}
Error_OperatorCannotBeApplied ();
return null;
}
}
//
// operator + (E e, U x)
// operator - (E e, U x)
//
if (oper == Operator.Addition || oper == Operator.Subtraction){
Type enum_type = lie ? l : r;
Type other_type = lie ? r : l;
Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
if (underlying_type != other_type){
temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
if (temp != null){
if (lie)
right = temp;
else
left = temp;
type = enum_type;
return this;
}
Error_OperatorCannotBeApplied ();
return null;
}
type = enum_type;
return this;
}
if (!rie){
temp = Convert.ImplicitConversion (ec, right, l, loc);
if (temp != null)
right = temp;
else {
Error_OperatorCannotBeApplied ();
return null;
}
} if (!lie){
temp = Convert.ImplicitConversion (ec, left, r, loc);
if (temp != null){
left = temp;
l = r;
} else {
Error_OperatorCannotBeApplied ();
return null;
}
}
if (oper == Operator.Equality || oper == Operator.Inequality ||
oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
if (left.Type != right.Type){
Error_OperatorCannotBeApplied ();
return null;
}
type = TypeManager.bool_type;
return this;
}
if (oper == Operator.BitwiseAnd ||
oper == Operator.BitwiseOr ||
oper == Operator.ExclusiveOr){
type = l;
return this;
}
Error_OperatorCannotBeApplied ();
return null;
}
if (oper == Operator.LeftShift || oper == Operator.RightShift)
return CheckShiftArguments (ec);
if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
type = TypeManager.bool_type;
return this;
}
if (l != r) {
Error_OperatorCannotBeApplied ();
return null;
}
Expression e = new ConditionalLogicalOperator (
oper == Operator.LogicalAnd, left, right, l, loc);
return e.Resolve (ec);
}
//
// operator & (bool x, bool y)
// operator | (bool x, bool y)
// operator ^ (bool x, bool y)
//
if (l == TypeManager.bool_type && r == TypeManager.bool_type){
if (oper == Operator.BitwiseAnd ||
oper == Operator.BitwiseOr ||
oper == Operator.ExclusiveOr){
type = l;
return this;
}
}
//
// Pointer comparison
//
if (l.IsPointer && r.IsPointer){
if (oper == Operator.Equality || oper == Operator.Inequality ||
oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
type = TypeManager.bool_type;
return this;
}
}
//
// This will leave left or right set to null if there is an error
//
bool check_user_conv = is_user_defined (l) && is_user_defined (r);
DoNumericPromotions (ec, l, r, check_user_conv);
if (left == null || right == null){
Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
return null;
}
//
// reload our cached types if required
//
l = left.Type;
r = right.Type;
if (oper == Operator.BitwiseAnd ||
oper == Operator.BitwiseOr ||
oper == Operator.ExclusiveOr){
if (l == r){
if (((l == TypeManager.int32_type) ||
(l == TypeManager.uint32_type) ||
(l == TypeManager.short_type) ||
(l == TypeManager.ushort_type) ||
(l == TypeManager.int64_type) ||
(l == TypeManager.uint64_type))){
type = l;
} else {
Error_OperatorCannotBeApplied ();
return null;
}
} else {
Error_OperatorCannotBeApplied ();
return null;
}
}
if (oper == Operator.Equality ||
oper == Operator.Inequality ||
oper == Operator.LessThanOrEqual ||
oper == Operator.LessThan ||
oper == Operator.GreaterThanOrEqual ||
oper == Operator.GreaterThan){
type = TypeManager.bool_type;
}
return this;
}
public override Expression DoResolve (EmitContext ec)
{
if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
left = ((ParenthesizedExpression) left).Expr;
left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
if (left == null)
return null;
if (left.eclass == ExprClass.Type) {
Error (75, "Casting a negative value needs to have the value in parentheses.");
return null;
}
} else
left = left.Resolve (ec);
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;
if (rc != null & lc != null){
Expression e = ConstantFold.BinaryFold (
ec, oper, lc, rc, loc);
if (e != null)
return e;
}
if (TypeManager.IsNullableType (left.Type) || TypeManager.IsNullableType (right.Type))
return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
return ResolveOperator (ec);
}
///
/// EmitBranchable is called from Statement.EmitBoolExpression in the
/// context of a conditional bool expression. This function will return
/// false if it is was possible to use EmitBranchable, or true if it was.
///
/// The expression's code is generated, and we will generate a branch to `target'
/// if the resulting expression value is equal to isTrue
///
public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
{
ILGenerator ig = ec.ig;
//
// This is more complicated than it looks, but its just to avoid
// duplicated tests: basically, we allow ==, !=, >, <, >= and <=
// but on top of that we want for == and != to use a special path
// if we are comparing against null
//
if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
//
// put the constant on the rhs, for simplicity
//
if (left is Constant) {
Expression swap = right;
right = left;
left = swap;
}
if (((Constant) right).IsZeroInteger) {
left.Emit (ec);
if (my_on_true)
ig.Emit (OpCodes.Brtrue, target);
else
ig.Emit (OpCodes.Brfalse, target);
return;
} else if (right is BoolConstant){
left.Emit (ec);
if (my_on_true != ((BoolConstant) right).Value)
ig.Emit (OpCodes.Brtrue, target);
else
ig.Emit (OpCodes.Brfalse, target);
return;
}
} else if (oper == Operator.LogicalAnd) {
if (onTrue) {
Label tests_end = ig.DefineLabel ();
left.EmitBranchable (ec, tests_end, false);
right.EmitBranchable (ec, target, true);
ig.MarkLabel (tests_end);
} else {
left.EmitBranchable (ec, target, false);
right.EmitBranchable (ec, target, false);
}
return;
} else if (oper == Operator.LogicalOr){
if (onTrue) {
left.EmitBranchable (ec, target, true);
right.EmitBranchable (ec, target, true);
} else {
Label tests_end = ig.DefineLabel ();
left.EmitBranchable (ec, tests_end, true);
right.EmitBranchable (ec, target, false);
ig.MarkLabel (tests_end);
}
return;
} else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
oper == Operator.Equality || oper == Operator.Inequality)) {
base.EmitBranchable (ec, target, onTrue);
return;
}
left.Emit (ec);
right.Emit (ec);
Type t = left.Type;
bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
switch (oper){
case Operator.Equality:
if (onTrue)
ig.Emit (OpCodes.Beq, target);
else
ig.Emit (OpCodes.Bne_Un, target);
break;
case Operator.Inequality:
if (onTrue)
ig.Emit (OpCodes.Bne_Un, target);
else
ig.Emit (OpCodes.Beq, target);
break;
case Operator.LessThan:
if (onTrue)
if (isUnsigned)
ig.Emit (OpCodes.Blt_Un, target);
else
ig.Emit (OpCodes.Blt, target);
else
if (isUnsigned)
ig.Emit (OpCodes.Bge_Un, target);
else
ig.Emit (OpCodes.Bge, target);
break;
case Operator.GreaterThan:
if (onTrue)
if (isUnsigned)
ig.Emit (OpCodes.Bgt_Un, target);
else
ig.Emit (OpCodes.Bgt, target);
else
if (isUnsigned)
ig.Emit (OpCodes.Ble_Un, target);
else
ig.Emit (OpCodes.Ble, target);
break;
case Operator.LessThanOrEqual:
if (onTrue)
if (isUnsigned)
ig.Emit (OpCodes.Ble_Un, target);
else
ig.Emit (OpCodes.Ble, target);
else
if (isUnsigned)
ig.Emit (OpCodes.Bgt_Un, target);
else
ig.Emit (OpCodes.Bgt, target);
break;
case Operator.GreaterThanOrEqual:
if (onTrue)
if (isUnsigned)
ig.Emit (OpCodes.Bge_Un, target);
else
ig.Emit (OpCodes.Bge, target);
else
if (isUnsigned)
ig.Emit (OpCodes.Blt_Un, target);
else
ig.Emit (OpCodes.Blt, target);
break;
default:
Console.WriteLine (oper);
throw new Exception ("what is THAT");
}
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
Type l = left.Type;
OpCode opcode;
//
// Handle short-circuit operators differently
// than the rest
//
if (oper == Operator.LogicalAnd) {
Label load_zero = ig.DefineLabel ();
Label end = ig.DefineLabel ();
left.EmitBranchable (ec, load_zero, false);
right.Emit (ec);
ig.Emit (OpCodes.Br, end);
ig.MarkLabel (load_zero);
ig.Emit (OpCodes.Ldc_I4_0);
ig.MarkLabel (end);
return;
} else if (oper == Operator.LogicalOr) {
Label load_one = ig.DefineLabel ();
Label end = ig.DefineLabel ();
left.EmitBranchable (ec, load_one, true);
right.Emit (ec);
ig.Emit (OpCodes.Br, end);
ig.MarkLabel (load_one);
ig.Emit (OpCodes.Ldc_I4_1);
ig.MarkLabel (end);
return;
}
left.Emit (ec);
right.Emit (ec);
bool isUnsigned = is_unsigned (left.Type);
switch (oper){
case Operator.Multiply:
if (ec.CheckState){
if (l == TypeManager.int32_type || l == TypeManager.int64_type)
opcode = OpCodes.Mul_Ovf;
else if (isUnsigned)
opcode = OpCodes.Mul_Ovf_Un;
else
opcode = OpCodes.Mul;
} else
opcode = OpCodes.Mul;
break;
case Operator.Division:
if (isUnsigned)
opcode = OpCodes.Div_Un;
else
opcode = OpCodes.Div;
break;
case Operator.Modulus:
if (isUnsigned)
opcode = OpCodes.Rem_Un;
else
opcode = OpCodes.Rem;
break;
case Operator.Addition:
if (ec.CheckState){
if (l == TypeManager.int32_type || l == TypeManager.int64_type)
opcode = OpCodes.Add_Ovf;
else if (isUnsigned)
opcode = OpCodes.Add_Ovf_Un;
else
opcode = OpCodes.Add;
} else
opcode = OpCodes.Add;
break;
case Operator.Subtraction:
if (ec.CheckState){
if (l == TypeManager.int32_type || l == TypeManager.int64_type)
opcode = OpCodes.Sub_Ovf;
else if (isUnsigned)
opcode = OpCodes.Sub_Ovf_Un;
else
opcode = OpCodes.Sub;
} else
opcode = OpCodes.Sub;
break;
case Operator.RightShift:
if (isUnsigned)
opcode = OpCodes.Shr_Un;
else
opcode = OpCodes.Shr;
break;
case Operator.LeftShift:
opcode = OpCodes.Shl;
break;
case Operator.Equality:
opcode = OpCodes.Ceq;
break;
case Operator.Inequality:
ig.Emit (OpCodes.Ceq);
ig.Emit (OpCodes.Ldc_I4_0);
opcode = OpCodes.Ceq;
break;
case Operator.LessThan:
if (isUnsigned)
opcode = OpCodes.Clt_Un;
else
opcode = OpCodes.Clt;
break;
case Operator.GreaterThan:
if (isUnsigned)
opcode = OpCodes.Cgt_Un;
else
opcode = OpCodes.Cgt;
break;
case Operator.LessThanOrEqual:
Type lt = left.Type;
if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
ig.Emit (OpCodes.Cgt_Un);
else
ig.Emit (OpCodes.Cgt);
ig.Emit (OpCodes.Ldc_I4_0);
opcode = OpCodes.Ceq;
break;
case Operator.GreaterThanOrEqual:
Type le = left.Type;
if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
ig.Emit (OpCodes.Clt_Un);
else
ig.Emit (OpCodes.Clt);
ig.Emit (OpCodes.Ldc_I4_0);
opcode = OpCodes.Ceq;
break;
case Operator.BitwiseOr:
opcode = OpCodes.Or;
break;
case Operator.BitwiseAnd:
opcode = OpCodes.And;
break;
case Operator.ExclusiveOr:
opcode = OpCodes.Xor;
break;
default:
throw new Exception ("This should not happen: Operator = "
+ oper.ToString ());
}
ig.Emit (opcode);
}
}
//
// Object created by Binary when the binary operator uses an method instead of being
// a binary operation that maps to a CIL binary operation.
//
public class BinaryMethod : Expression {
public MethodBase method;
public ArrayList Arguments;
public BinaryMethod (Type t, MethodBase m, ArrayList args)
{
method = m;
Arguments = args;
type = t;
eclass = ExprClass.Value;
}
public override Expression DoResolve (EmitContext ec)
{
return this;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
if (Arguments != null)
Invocation.EmitArguments (ec, method, Arguments, false, null);
if (method is MethodInfo)
ig.Emit (OpCodes.Call, (MethodInfo) method);
else
ig.Emit (OpCodes.Call, (ConstructorInfo) method);
}
}
//
// Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
// b, c, d... may be strings or objects.
//
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)
{
this.loc = loc;
type = TypeManager.string_type;
eclass = ExprClass.Value;
operands = new ArrayList (2);
Append (ec, left);
Append (ec, right);
}
public override Expression DoResolve (EmitContext ec)
{
if (invalid)
return null;
return this;
}
public void Append (EmitContext ec, Expression operand)
{
//
// Constant folding
//
if (operand is StringConstant && operands.Count != 0) {
StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
if (last_operand != null) {
operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
return;
}
}
//
// Conversion to object
//
if (operand.Type != TypeManager.string_type) {
Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
if (no == null) {
Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
invalid = true;
}
operand = no;
}
operands.Add (operand);
}
public override void Emit (EmitContext ec)
{
MethodInfo concat_method = null;
//
// Do conversion to arguments; check for strings only
//
// 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;
}
for (int i = 0; i < operands.Count; i ++) {
Expression e = (Expression) operands [i];
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);
}
}
//
// Find the right method
//
switch (operands.Count) {
case 1:
//
// This should not be possible, because simple constant folding
// is taken care of in the Binary code.
//
throw new Exception ("how did you get here?");
case 2:
concat_method = is_strings_only ?
TypeManager.string_concat_string_string :
TypeManager.string_concat_object_object ;
break;
case 3:
concat_method = is_strings_only ?
TypeManager.string_concat_string_string_string :
TypeManager.string_concat_object_object_object ;
break;
case 4:
//
// There is not a 4 param overlaod for object (the one that there is
// is actually a varargs methods, and is only in corlib because it was
// introduced there before.).
//
if (!is_strings_only)
goto default;
concat_method = TypeManager.string_concat_string_string_string_string;
break;
default:
concat_method = is_strings_only ?
TypeManager.string_concat_string_dot_dot_dot :
TypeManager.string_concat_object_dot_dot_dot ;
break;
}
Invocation.EmitArguments (ec, concat_method, operands, false, null);
ec.ig.Emit (OpCodes.Call, concat_method);
}
}
//
// Object created with +/= on delegates
//
public class BinaryDelegate : Expression {
MethodInfo method;
ArrayList args;
public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
{
method = mi;
this.args = args;
type = t;
eclass = ExprClass.Value;
}
public override Expression DoResolve (EmitContext ec)
{
return this;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
Invocation.EmitArguments (ec, method, args, false, null);
ig.Emit (OpCodes.Call, (MethodInfo) method);
ig.Emit (OpCodes.Castclass, type);
}
public Expression Right {
get {
Argument arg = (Argument) args [1];
return arg.Expr;
}
}
public bool IsAddition {
get {
return method == TypeManager.delegate_combine_delegate_delegate;
}
}
}
//
// User-defined conditional logical operator
public class ConditionalLogicalOperator : Expression {
Expression left, right;
bool is_and;
public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
{
type = t;
eclass = ExprClass.Value;
this.loc = loc;
this.left = left;
this.right = right;
this.is_and = is_and;
}
protected void Error19 ()
{
Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
}
protected void Error218 ()
{
Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
"declarations of operator true and operator false");
}
Expression op_true, op_false, op;
LocalTemporary left_temp;
public override Expression DoResolve (EmitContext ec)
{
MethodInfo method;
Expression operator_group;
operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
if (operator_group == null) {
Error19 ();
return null;
}
left_temp = new LocalTemporary (ec, type);
ArrayList arguments = new ArrayList ();
arguments.Add (new Argument (left_temp, Argument.AType.Expression));
arguments.Add (new Argument (right, Argument.AType.Expression));
method = Invocation.OverloadResolve (
ec, (MethodGroupExpr) operator_group, arguments, false, loc)
as MethodInfo;
if (method == null) {
Error19 ();
return null;
}
if (method.ReturnType != type) {
Report.Error (217, loc, "In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') " +
"must have the same return type as the type of its 2 parameters", TypeManager.CSharpSignature (method));
return null;
}
op = new StaticCallExpr (method, arguments, loc);
op_true = GetOperatorTrue (ec, left_temp, loc);
op_false = GetOperatorFalse (ec, left_temp, loc);
if ((op_true == null) || (op_false == null)) {
Error218 ();
return null;
}
return this;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
Label false_target = ig.DefineLabel ();
Label end_target = ig.DefineLabel ();
left.Emit (ec);
left_temp.Store (ec);
(is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
left_temp.Emit (ec);
ig.Emit (OpCodes.Br, end_target);
ig.MarkLabel (false_target);
op.Emit (ec);
ig.MarkLabel (end_target);
}
}
public class PointerArithmetic : Expression {
Expression left, right;
bool is_add;
//
// We assume that `l' is always a pointer
//
public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
{
type = t;
this.loc = loc;
left = l;
right = r;
is_add = is_addition;
}
public override Expression DoResolve (EmitContext ec)
{
eclass = ExprClass.Variable;
if (left.Type == TypeManager.void_ptr_type) {
Error (242, "The operation in question is undefined on void pointers");
return null;
}
return this;
}
public override void Emit (EmitContext ec)
{
Type op_type = left.Type;
ILGenerator ig = ec.ig;
// It must be either array or fixed buffer
Type element = TypeManager.HasElementType (op_type) ?
element = TypeManager.GetElementType (op_type) :
element = AttributeTester.GetFixedBuffer (((FieldExpr)left).FieldInfo).ElementType;
int size = GetTypeSize (element);
Type rtype = right.Type;
if (rtype.IsPointer){
//
// handle (pointer - pointer)
//
left.Emit (ec);
right.Emit (ec);
ig.Emit (OpCodes.Sub);
if (size != 1){
if (size == 0)
ig.Emit (OpCodes.Sizeof, element);
else
IntLiteral.EmitInt (ig, size);
ig.Emit (OpCodes.Div);
}
ig.Emit (OpCodes.Conv_I8);
} else {
//
// handle + and - on (pointer op int)
//
left.Emit (ec);
ig.Emit (OpCodes.Conv_I);
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)
ig.Emit (OpCodes.Conv_I);
if (is_add)
ig.Emit (OpCodes.Add);
else
ig.Emit (OpCodes.Sub);
}
}
}
///
/// Implements the ternary conditional operator (?:)
///
public class Conditional : Expression {
Expression expr, trueExpr, falseExpr;
public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
{
this.expr = expr;
this.trueExpr = trueExpr;
this.falseExpr = falseExpr;
this.loc = l;
}
public Expression Expr {
get {
return expr;
}
}
public Expression TrueExpr {
get {
return trueExpr;
}
}
public Expression FalseExpr {
get {
return falseExpr;
}
}
public override Expression DoResolve (EmitContext ec)
{
expr = expr.Resolve (ec);
if (expr == null)
return null;
if (TypeManager.IsNullableType (expr.Type))
return new Nullable.LiftedConditional (expr, trueExpr, falseExpr, loc).Resolve (ec);
if (expr.Type != TypeManager.bool_type){
expr = Expression.ResolveBoolean (
ec, expr, loc);
if (expr == null)
return null;
}
trueExpr = trueExpr.Resolve (ec);
falseExpr = falseExpr.Resolve (ec);
if (trueExpr == null || falseExpr == null)
return null;
eclass = ExprClass.Value;
if (trueExpr.Type == falseExpr.Type)
type = trueExpr.Type;
else {
Expression conv;
Type true_type = trueExpr.Type;
Type false_type = falseExpr.Type;
//
// First, if an implicit conversion exists from trueExpr
// to falseExpr, then the result type is of type falseExpr.Type
//
conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
if (conv != null){
//
// Check if both can convert implicitl to each other's type
//
if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
Error (172,
"Can not compute type of conditional expression " +
"as `" + TypeManager.CSharpName (trueExpr.Type) +
"' and `" + TypeManager.CSharpName (falseExpr.Type) +
"' convert implicitly to each other");
return null;
}
type = false_type;
trueExpr = conv;
} else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
type = true_type;
falseExpr = conv;
} else {
Error (173, "The type of the conditional expression can " +
"not be computed because there is no implicit conversion" +
" from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
" and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
return null;
}
}
// Dead code optimalization
if (expr is BoolConstant){
BoolConstant bc = (BoolConstant) expr;
Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
return bc.Value ? trueExpr : falseExpr;
}
return this;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
Label false_target = ig.DefineLabel ();
Label end_target = ig.DefineLabel ();
expr.EmitBranchable (ec, false_target, false);
trueExpr.Emit (ec);
ig.Emit (OpCodes.Br, end_target);
ig.MarkLabel (false_target);
falseExpr.Emit (ec);
ig.MarkLabel (end_target);
}
}
///
/// Local variables
///
public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
public readonly string Name;
public readonly Block Block;
public LocalInfo local_info;
bool is_readonly;
bool prepared;
LocalTemporary temp;
public LocalVariableReference (Block block, string name, Location l)
{
Block = block;
Name = name;
loc = l;
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)
{
this.local_info = local_info;
this.is_readonly = is_readonly;
}
public VariableInfo VariableInfo {
get {
return local_info.VariableInfo;
}
}
public bool IsReadOnly {
get {
return is_readonly;
}
}
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;
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;
eclass = ExprClass.Value;
return e.Resolve (ec);
}
if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
return null;
if (lvalue_right_side == null)
local_info.Used = true;
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)
{
return DoResolveBase (ec, null);
}
override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
Expression ret = DoResolveBase (ec, right_side);
if (ret != null)
CheckObsoleteAttribute (ret.Type);
return ret;
}
public bool VerifyFixed (bool is_expression)
{
return !is_expression || local_info.IsFixed;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
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){
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)
{
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;
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 ()
{
return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
}
}
///
/// This represents a reference to a parameter in the intermediate
/// representation.
///
public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
Parameters pars;
String name;
int idx;
Block block;
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)
{
this.pars = pars;
this.block = block;
this.idx = idx;
this.name = name;
this.loc = loc;
eclass = ExprClass.Variable;
}
public VariableInfo VariableInfo {
get { return vi; }
}
public bool VerifyFixed (bool is_expression)
{
return !is_expression || TypeManager.IsValueType (type);
}
public bool IsAssigned (EmitContext ec, Location loc)
{
if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
return true;
Report.Error (165, loc,
"Use of unassigned parameter `" + name + "'");
return false;
}
public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
{
if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
return true;
Report.Error (170, loc,
"Use of possibly unassigned field `" + field_name + "'");
return false;
}
public void SetAssigned (EmitContext ec)
{
if (is_out && ec.DoFlowAnalysis)
ec.CurrentBranching.SetAssigned (vi);
}
public void SetFieldAssigned (EmitContext ec, string field_name)
{
if (is_out && ec.DoFlowAnalysis)
ec.CurrentBranching.SetFieldAssigned (vi, field_name);
}
protected void DoResolveBase (EmitContext ec)
{
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);
}
}
}
//
// Notice that for ref/out parameters, the type exposed is not the
// same type exposed externally.
//
// for "ref int a":
// externally we expose "int&"
// here we expose "int".
//
// We record this in "is_ref". This means that the type system can treat
// the type as it is expected, but when we generate the code, we generate
// the alternate kind of code.
//
public override Expression DoResolve (EmitContext ec)
{
DoResolveBase (ec);
if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
return null;
if (ec.RemapToProxy)
return ec.RemapParameter (idx);
return this;
}
override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
DoResolveBase (ec);
SetAssigned (ec);
if (ec.RemapToProxy)
return ec.RemapParameterLValue (idx, right_side);
return this;
}
static public void EmitLdArg (ILGenerator ig, int x)
{
if (x <= 255){
switch (x){
case 0: ig.Emit (OpCodes.Ldarg_0); break;
case 1: ig.Emit (OpCodes.Ldarg_1); break;
case 2: ig.Emit (OpCodes.Ldarg_2); break;
case 3: ig.Emit (OpCodes.Ldarg_3); break;
default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
}
} else
ig.Emit (OpCodes.Ldarg, x);
}
//
// This method is used by parameters that are references, that are
// being passed as references: we only want to pass the pointer (that
// is already stored in the parameter, not the address of the pointer,
// and not the value of the variable).
//
public void EmitLoad (EmitContext ec)
{
ILGenerator ig = ec.ig;
int arg_idx = idx;
if (!ec.MethodIsStatic)
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.MethodIsStatic)
arg_idx++;
EmitLdArg (ig, arg_idx);
if (is_ref) {
if (prepared)
ec.ig.Emit (OpCodes.Dup);
//
// If we are a reference, we loaded on the stack a pointer
// Now lets load the real value
//
LoadFromPtr (ig, type);
}
if (leave_copy) {
ec.ig.Emit (OpCodes.Dup);
if (is_ref) {
temp = new LocalTemporary (ec, type);
temp.Store (ec);
}
}
}
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;
prepared = prepare_for_load;
if (!ec.MethodIsStatic)
arg_idx++;
if (is_ref && !prepared)
EmitLdArg (ig, arg_idx);
source.Emit (ec);
if (leave_copy)
ec.ig.Emit (OpCodes.Dup);
if (is_ref) {
if (leave_copy) {
temp = new LocalTemporary (ec, type);
temp.Store (ec);
}
StoreFromPtr (ig, type);
if (temp != null)
temp.Emit (ec);
} else {
if (arg_idx <= 255)
ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
else
ig.Emit (OpCodes.Starg, arg_idx);
}
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
ec.EmitAddressOfParameter (name);
return;
}
int arg_idx = idx;
if (!ec.MethodIsStatic)
arg_idx++;
if (is_ref){
if (arg_idx <= 255)
ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
else
ec.ig.Emit (OpCodes.Ldarg, arg_idx);
} else {
if (arg_idx <= 255)
ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
else
ec.ig.Emit (OpCodes.Ldarga, arg_idx);
}
}
}
///
/// Used for arguments to New(), Invocation()
///
public class Argument {
public enum AType : byte {
Expression,
Ref,
Out,
ArgList
};
public readonly AType ArgType;
public Expression Expr;
public Argument (Expression expr, AType type)
{
this.Expr = expr;
this.ArgType = type;
}
public Argument (Expression expr)
{
this.Expr = expr;
this.ArgType = AType.Expression;
}
public Type Type {
get {
if (ArgType == AType.Ref || ArgType == AType.Out)
return TypeManager.GetReferenceType (Expr.Type);
else
return Expr.Type;
}
}
public Parameter.Modifier GetParameterModifier ()
{
switch (ArgType) {
case AType.Out:
return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
case AType.Ref:
return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
default:
return Parameter.Modifier.NONE;
}
}
public static string FullDesc (Argument a)
{
if (a.ArgType == AType.ArgList)
return "__arglist";
return (a.ArgType == AType.Ref ? "ref " :
(a.ArgType == AType.Out ? "out " : "")) +
TypeManager.CSharpName (a.Expr.Type);
}
public bool ResolveMethodGroup (EmitContext ec, Location loc)
{
SimpleName sn = Expr as SimpleName;
if (sn != null)
Expr = sn.GetMethodGroup ();
// FIXME: csc doesn't report any error if you try to use `ref' or
// `out' in a delegate creation expression.
Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
if (Expr == null)
return false;
return true;
}
void Error_LValueRequired (Location loc)
{
Report.Error (1510, loc, "An lvalue is required as an argument to out or ref");
}
public bool Resolve (EmitContext ec, Location loc)
{
if (ArgType == AType.Ref) {
Expr = Expr.Resolve (ec);
if (Expr == null)
return false;
if (!ec.IsConstructor) {
FieldExpr fe = Expr as FieldExpr;
if (fe != null && fe.FieldInfo.IsInitOnly) {
if (fe.FieldInfo.IsStatic)
Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
else
Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
return false;
}
}
Expr = Expr.DoResolveLValue (ec, Expr);
if (Expr == null)
Error_LValueRequired (loc);
} else if (ArgType == AType.Out) {
Expr = Expr.DoResolveLValue (ec, EmptyExpression.Null);
if (Expr == null)
Error_LValueRequired (loc);
}
else
Expr = Expr.Resolve (ec);
if (Expr == null)
return false;
if (Expr is IMemberExpr) {
IMemberExpr me = Expr as IMemberExpr;
//
// This can happen with the following code:
//
// class X {}
// class Y {
// public Y (X x) {}
// }
// class Z : Y {
// X X;
// public Z () : base (X) {}
// }
//
// SimpleNameResolve is conservative about flagging the X as
// an error since it has identical name and type. However,
// because there's no MemberAccess, that is not really justified.
// It is still simpler to fix it here, rather than in SimpleNameResolve.
//
if (me.IsInstance && me.InstanceExpression == null) {
SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
return false;
}
}
if (ArgType == AType.Expression)
return true;
else {
//
// Catch errors where fields of a MarshalByRefObject are passed as ref or out
// This is only allowed for `this'
//
FieldExpr fe = Expr as FieldExpr;
if (fe != null && !fe.IsStatic){
Expression instance = fe.InstanceExpression;
if (instance.GetType () != typeof (This)){
if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
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;
}
}
}
}
if (Expr.eclass != ExprClass.Variable){
//
// We just probe to match the CSC output
//
if (Expr.eclass == ExprClass.PropertyAccess ||
Expr.eclass == ExprClass.IndexerAccess){
Report.Error (
206, loc,
"A property or indexer can not be passed as an out or ref " +
"parameter");
} else {
Error_LValueRequired (loc);
}
return false;
}
return true;
}
public void Emit (EmitContext ec)
{
//
// Ref and Out parameters need to have their addresses taken.
//
// ParameterReferences might already be references, so we want
// to pass just the value
//
if (ArgType == AType.Ref || ArgType == AType.Out){
AddressOp mode = AddressOp.Store;
if (ArgType == AType.Ref)
mode |= AddressOp.Load;
if (Expr is ParameterReference){
ParameterReference pr = (ParameterReference) Expr;
if (pr.IsRef)
pr.EmitLoad (ec);
else {
pr.AddressOf (ec, mode);
}
} else {
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);
}
}
///
/// Invocation of methods or delegates.
///
public class Invocation : ExpressionStatement {
public readonly ArrayList Arguments;
Expression expr;
MethodBase method = null;
//
// arguments is an ArrayList, but we do not want to typecast,
// as it might be null.
//
// FIXME: only allow expr to be a method invocation or a
// delegate invocation (7.5.5)
//
public Invocation (Expression expr, ArrayList arguments, Location l)
{
this.expr = expr;
Arguments = arguments;
loc = l;
}
public Expression Expr {
get {
return expr;
}
}
///
/// Determines "better conversion" as specified in 7.4.2.3
///
/// Returns : p if a->p is better,
/// q if a->q is better,
/// null if neither is better
///
static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
{
Type argument_type = TypeManager.TypeToCoreType (a.Type);
Expression argument_expr = a.Expr;
// p = TypeManager.TypeToCoreType (p);
// q = TypeManager.TypeToCoreType (q);
if (argument_type == null)
throw new Exception ("Expression of type " + a.Expr +
" does not resolve its type");
if (p == null || q == null)
throw new InternalErrorException ("BetterConversion Got a null conversion");
if (p == q)
return null;
if (argument_expr is NullLiteral) {
//
// If the argument is null and one of the types to compare is 'object' and
// the other is a reference type, we prefer the other.
//
// This follows from the usual rules:
// * There is an implicit conversion from 'null' to type 'object'
// * There is an implicit conversion from 'null' to any reference type
// * There is an implicit conversion from any reference type to type 'object'
// * 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 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;
if (!q.IsValueType && p == TypeManager.object_type)
return q;
}
if (argument_type == p)
return p;
if (argument_type == q)
return q;
Expression p_tmp = new EmptyExpression (p);
Expression q_tmp = new EmptyExpression (q);
bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
if (p_to_q && !q_to_p)
return p;
if (q_to_p && !p_to_q)
return q;
if (p == TypeManager.sbyte_type)
if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
q == TypeManager.uint32_type || q == TypeManager.uint64_type)
return p;
if (q == TypeManager.sbyte_type)
if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
p == TypeManager.uint32_type || p == TypeManager.uint64_type)
return q;
if (p == TypeManager.short_type)
if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
q == TypeManager.uint64_type)
return p;
if (q == TypeManager.short_type)
if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
p == TypeManager.uint64_type)
return q;
if (p == TypeManager.int32_type)
if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
return p;
if (q == TypeManager.int32_type)
if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
return q;
if (p == TypeManager.int64_type)
if (q == TypeManager.uint64_type)
return p;
if (q == TypeManager.int64_type)
if (p == TypeManager.uint64_type)
return q;
return null;
}
///
/// Determines "Better function" between candidate
/// and the current best match
///
///
/// Returns a boolean indicating :
/// false if candidate ain't better
/// true if candidate is better than the current best match
///
static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
MethodBase candidate, bool candidate_params,
MethodBase best, bool best_params, Location loc)
{
ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
ParameterData best_pd = TypeManager.GetParameterData (best);
bool better_at_least_one = false;
bool same = true;
for (int j = 0; j < argument_count; ++j) {
Argument a = (Argument) args [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)
ct = TypeManager.GetElementType (ct);
if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
if (best_params)
bt = TypeManager.GetElementType (bt);
if (ct.Equals (bt))
continue;
same = false;
Type better = BetterConversion (ec, a, ct, bt, loc);
// for each argument, the conversion to 'ct' should be no worse than
// the conversion to 'bt'.
if (better == bt)
return false;
// for at least one argument, the conversion to 'ct' should be better than
// the conversion to 'bt'.
if (better == ct)
better_at_least_one = true;
}
if (better_at_least_one)
return true;
if (!same)
return false;
//
// If two methods have equal parameter types, but
// only one of them is generic, the non-generic one wins.
//
if (TypeManager.IsGenericMethod (best) && !TypeManager.IsGenericMethod (candidate))
return true;
else if (!TypeManager.IsGenericMethod (best) && TypeManager.IsGenericMethod (candidate))
return false;
//
// Note that this is not just an optimization. This handles the case
// This handles the case
//
// Add (float f1, float f2, float f3);
// Add (params decimal [] foo);
//
// The call Add (3, 4, 5) should be ambiguous. Without this check, the
// first candidate would've chosen as better.
//
//
// This handles the following cases:
//
// Trim () is better than Trim (params char[] chars)
// Concat (string s1, string s2, string s3) is better than
// Concat (string s1, params string [] srest)
//
return !candidate_params && best_params;
}
static bool IsOverride (MethodBase cand_method, MethodBase base_method)
{
if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
return false;
ParameterData cand_pd = TypeManager.GetParameterData (cand_method);
ParameterData base_pd = TypeManager.GetParameterData (base_method);
if (cand_pd.Count != base_pd.Count)
return false;
for (int j = 0; j < cand_pd.Count; ++j) {
Parameter.Modifier cm = cand_pd.ParameterModifier (j);
Parameter.Modifier bm = base_pd.ParameterModifier (j);
Type ct = TypeManager.TypeToCoreType (cand_pd.ParameterType (j));
Type bt = TypeManager.TypeToCoreType (base_pd.ParameterType (j));
if (cm != bm || ct != bt)
return false;
}
return true;
}
public static string FullMethodDesc (MethodBase mb)
{
string ret_type = "";
if (mb == null)
return "";
if (mb is MethodInfo)
ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
StringBuilder sb = new StringBuilder (ret_type);
sb.Append (" ");
sb.Append (mb.ReflectedType.ToString ());
sb.Append (".");
sb.Append (mb.Name);
ParameterData pd = TypeManager.GetParameterData (mb);
int count = pd.Count;
sb.Append (" (");
for (int i = count; i > 0; ) {
i--;
sb.Append (pd.ParameterDesc (count - i - 1));
if (i != 0)
sb.Append (", ");
}
sb.Append (")");
return sb.ToString ();
}
public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
{
MemberInfo [] miset;
MethodGroupExpr union;
if (mg1 == null) {
if (mg2 == null)
return null;
return (MethodGroupExpr) mg2;
} else {
if (mg2 == null)
return (MethodGroupExpr) mg1;
}
MethodGroupExpr left_set = null, right_set = null;
int length1 = 0, length2 = 0;
left_set = (MethodGroupExpr) mg1;
length1 = left_set.Methods.Length;
right_set = (MethodGroupExpr) mg2;
length2 = right_set.Methods.Length;
ArrayList common = new ArrayList ();
foreach (MethodBase r in right_set.Methods){
if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
common.Add (r);
}
miset = new MemberInfo [length1 + length2 - common.Count];
left_set.Methods.CopyTo (miset, 0);
int k = length1;
foreach (MethodBase r in right_set.Methods) {
if (!common.Contains (r))
miset [k++] = r;
}
union = new MethodGroupExpr (miset, loc);
return union;
}
public static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
ArrayList arguments, int arg_count,
ref MethodBase candidate)
{
return IsParamsMethodApplicable (
ec, me, arguments, arg_count, false, ref candidate) ||
IsParamsMethodApplicable (
ec, me, arguments, arg_count, true, ref candidate);
}
static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
ArrayList arguments, int arg_count,
bool do_varargs, ref MethodBase candidate)
{
if (!me.HasTypeArguments &&
!TypeManager.InferParamsTypeArguments (ec, arguments, ref candidate))
return false;
return IsParamsMethodApplicable (
ec, arguments, arg_count, candidate, do_varargs);
}
///
/// Determines if the candidate method, if a params method, is applicable
/// in its expanded form to the given set of arguments
///
static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
int arg_count, MethodBase candidate,
bool do_varargs)
{
ParameterData pd = TypeManager.GetParameterData (candidate);
int pd_count = pd.Count;
if (pd_count == 0)
return false;
int count = pd_count - 1;
if (do_varargs) {
if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
return false;
if (pd_count != arg_count)
return false;
} else {
if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
return false;
}
if (count > arg_count)
return false;
if (pd_count == 1 && arg_count == 0)
return true;
//
// If we have come this far, the case which
// remains is when the number of parameters is
// less than or equal to the argument count.
//
for (int i = 0; i < count; ++i) {
Argument a = (Argument) arguments [i];
Parameter.Modifier a_mod = a.GetParameterModifier () &
(unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
Parameter.Modifier p_mod = pd.ParameterModifier (i) &
(unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
if (a_mod == p_mod) {
if (a_mod == Parameter.Modifier.NONE)
if (!Convert.ImplicitConversionExists (ec,
a.Expr,
pd.ParameterType (i)))
return false;
if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
Type pt = pd.ParameterType (i);
if (!pt.IsByRef)
pt = TypeManager.GetReferenceType (pt);
if (pt != a.Type)
return false;
}
} else
return false;
}
if (do_varargs) {
Argument a = (Argument) arguments [count];
if (!(a.Expr is Arglist))
return false;
return true;
}
Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
for (int i = pd_count - 1; i < arg_count; i++) {
Argument a = (Argument) arguments [i];
if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
return false;
}
return true;
}
public static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
ArrayList arguments, int arg_count,
ref MethodBase candidate)
{
if (!me.HasTypeArguments &&
!TypeManager.InferTypeArguments (ec, arguments, ref candidate))
return false;
return IsApplicable (ec, arguments, arg_count, candidate);
}
///
/// Determines if the candidate method is applicable (section 14.4.2.1)
/// to the given set of arguments
///
static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
MethodBase candidate)
{
ParameterData pd = TypeManager.GetParameterData (candidate);
if (arg_count != pd.Count)
return false;
for (int i = arg_count; i > 0; ) {
i--;
Argument a = (Argument) arguments [i];
Parameter.Modifier a_mod = a.GetParameterModifier () &
unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
Parameter.Modifier p_mod = pd.ParameterModifier (i) &
unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
if (a_mod == p_mod ||
(a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
if (a_mod == Parameter.Modifier.NONE) {
if (!Convert.ImplicitConversionExists (ec,
a.Expr,
pd.ParameterType (i)))
return false;
}
if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
Type pt = pd.ParameterType (i);
if (!pt.IsByRef)
pt = TypeManager.GetReferenceType (pt);
if (pt != a.Type)
return false;
}
} else
return false;
}
return true;
}
static private bool IsAncestralType (Type first_type, Type second_type)
{
return first_type != second_type &&
(second_type.IsSubclassOf (first_type) ||
TypeManager.ImplementsInterface (second_type, first_type));
}
///
/// Find the Applicable Function Members (7.4.2.1)
///
/// me: Method Group expression with the members to select.
/// it might contain constructors or methods (or anything
/// that maps to a method).
///
/// Arguments: ArrayList containing resolved Argument objects.
///
/// loc: The location if we want an error to be reported, or a Null
/// location for "probing" purposes.
///
/// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
/// that is the best match of me on Arguments.
///
///
public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
ArrayList Arguments, bool may_fail,
Location loc)
{
MethodBase method = null;
bool method_params = false;
Type applicable_type = null;
int arg_count = 0;
ArrayList candidates = new ArrayList ();
ArrayList candidate_overrides = new ArrayList ();
//
// Used to keep a map between the candidate
// and whether it is being considered in its
// normal or expanded form
//
// false is normal form, true is expanded form
//
Hashtable candidate_to_form = null;
if (Arguments != null)
arg_count = Arguments.Count;
if ((me.Name == "Invoke") &&
TypeManager.IsDelegateType (me.DeclaringType)) {
Error_InvokeOnDelegate (loc);
return null;
}
MethodBase[] methods = me.Methods;
//
// First we construct the set of applicable methods
//
bool is_sorted = true;
for (int i = 0; i < methods.Length; i++){
Type decl_type = methods [i].DeclaringType;
//
// If we have already found an applicable method
// we eliminate all base types (Section 14.5.5.1)
//
if ((applicable_type != null) &&
IsAncestralType (decl_type, applicable_type))
continue;
//
// Methods marked 'override' don't take part in 'applicable_type'
// computation, nor in the actual overload resolution.
// However, they still need to be emitted instead of a base virtual method.
// We avoid doing the 'applicable' test here, since it'll anyway be applied
// to the base virtual function, and IsOverride is much faster than IsApplicable.
//
if (!me.IsBase &&
methods [i].IsVirtual &&
(methods [i].Attributes & MethodAttributes.NewSlot) == 0) {
candidate_overrides.Add (methods [i]);
continue;
}
//
// Check if candidate is applicable (section 14.4.2.1)
// Is candidate applicable in normal form?
//
bool is_applicable = IsApplicable (
ec, me, Arguments, arg_count, ref methods [i]);
if (!is_applicable &&
(IsParamsMethodApplicable (
ec, me, Arguments, arg_count, ref methods [i]))) {
MethodBase candidate = methods [i];
if (candidate_to_form == null)
candidate_to_form = new PtrHashtable ();
candidate_to_form [candidate] = candidate;
// Candidate is applicable in expanded form
is_applicable = true;
}
if (!is_applicable)
continue;
candidates.Add (methods [i]);
if (applicable_type == null)
applicable_type = decl_type;
else if (applicable_type != decl_type) {
is_sorted = false;
if (IsAncestralType (applicable_type, decl_type))
applicable_type = decl_type;
}
}
int candidate_top = candidates.Count;
if (applicable_type == null) {
//
// Okay so we have failed to find anything so we
// return by providing info about the closest match
//
for (int i = 0; i < methods.Length; ++i) {
MethodBase c = (MethodBase) methods [i];
ParameterData pd = TypeManager.GetParameterData (c);
if (pd.Count != arg_count)
continue;
if (!TypeManager.InferTypeArguments (ec, Arguments, ref c))
continue;
VerifyArgumentsCompat (ec, Arguments, arg_count,
c, false, null, may_fail, loc);
break;
}
if (!may_fail) {
string report_name = me.Name;
if (report_name == ".ctor")
report_name = me.DeclaringType.ToString ();
for (int i = 0; i < methods.Length; ++i) {
MethodBase c = methods [i];
ParameterData pd = TypeManager.GetParameterData (c);
if (pd.Count != arg_count)
continue;
if (TypeManager.InferTypeArguments (ec, Arguments, ref c))
continue;
Report.Error (
411, loc, "The type arguments for " +
"method `{0}' cannot be infered from " +
"the usage. Try specifying the type " +
"arguments explicitly.", report_name);
return null;
}
Error_WrongNumArguments (
loc, report_name, arg_count);
return null;
}
return null;
}
if (!is_sorted) {
//
// At this point, applicable_type is _one_ of the most derived types
// in the set of types containing the methods in this MethodGroup.
// Filter the candidates so that they only contain methods from the
// most derived types.
//
int finalized = 0; // Number of finalized candidates
do {
// Invariant: applicable_type is a most derived type
// We'll try to complete Section 14.5.5.1 for 'applicable_type' by
// eliminating all it's base types. At the same time, we'll also move
// every unrelated type to the end of the array, and pick the next
// 'applicable_type'.
Type next_applicable_type = null;
int j = finalized; // where to put the next finalized candidate
int k = finalized; // where to put the next undiscarded candidate
for (int i = finalized; i < candidate_top; ++i) {
MethodBase candidate = (MethodBase) candidates [i];
Type decl_type = candidate.DeclaringType;
if (decl_type == applicable_type) {
candidates [k++] = candidates [j];
candidates [j++] = candidates [i];
continue;
}
if (IsAncestralType (decl_type, applicable_type))
continue;
if (next_applicable_type != null &&
IsAncestralType (decl_type, next_applicable_type))
continue;
candidates [k++] = candidates [i];
if (next_applicable_type == null ||
IsAncestralType (next_applicable_type, decl_type))
next_applicable_type = decl_type;
}
applicable_type = next_applicable_type;
finalized = j;
candidate_top = k;
} while (applicable_type != null);
}
//
// Now we actually find the best method
//
method = (MethodBase) candidates [0];
method_params = candidate_to_form != null && candidate_to_form.Contains (method);
for (int ix = 1; ix < candidate_top; ix++){
MethodBase candidate = (MethodBase) candidates [ix];
if (candidate == method)
continue;
bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
if (BetterFunction (ec, Arguments, arg_count,
candidate, cand_params,
method, method_params, loc)) {
method = candidate;
method_params = cand_params;
}
}
//
// Now check that there are no ambiguities i.e the selected method
// should be better than all the others
//
bool ambiguous = false;
for (int ix = 0; ix < candidate_top; ix++){
MethodBase candidate = (MethodBase) candidates [ix];
if (candidate == method)
continue;
bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
if (!BetterFunction (ec, Arguments, arg_count,
method, method_params,
candidate, cand_params,
loc)) {
Report.SymbolRelatedToPreviousError (candidate);
ambiguous = true;
}
}
if (ambiguous) {
Report.SymbolRelatedToPreviousError (method);
Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
return null;
}
//
// If the method is a virtual function, pick an override closer to the LHS type.
//
if (!me.IsBase && method.IsVirtual) {
if ((method.Attributes & MethodAttributes.NewSlot) != MethodAttributes.NewSlot)
throw new InternalErrorException (
"Should not happen. An 'override' method took part in overload resolution: " + method);
foreach (MethodBase candidate in candidate_overrides) {
if (IsOverride (candidate, method))
method = candidate;
}
}
//
// And now check if the arguments are all
// compatible, perform conversions if
// necessary etc. and return if everything is
// all right
//
if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
method_params, null, may_fail, loc))
return null;
return method;
}
static void Error_WrongNumArguments (Location loc, String name, int arg_count)
{
Report.Error (1501, loc,
"No overload for method `" + name + "' takes `" +
arg_count + "' arguments");
}
static void Error_InvokeOnDelegate (Location loc)
{
Report.Error (1533, loc,
"Invoke cannot be called directly on a delegate");
}
static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
Type delegate_type, string arg_sig, string par_desc)
{
if (delegate_type == null)
Report.Error (1502, loc,
"The best overloaded match for method '" +
FullMethodDesc (method) +
"' has some invalid arguments");
else
Report.Error (1594, loc,
"Delegate '" + delegate_type.ToString () +
"' has some invalid arguments.");
Report.Error (1503, loc,
String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
idx, arg_sig, par_desc));
}
public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
int arg_count, MethodBase method,
bool chose_params_expanded,
Type delegate_type, bool may_fail,
Location loc)
{
ParameterData pd = TypeManager.GetParameterData (method);
int pd_count = pd.Count;
for (int j = 0; j < arg_count; j++) {
Argument a = (Argument) Arguments [j];
Expression a_expr = a.Expr;
Type parameter_type = pd.ParameterType (j);
Parameter.Modifier pm = pd.ParameterModifier (j);
if (pm == Parameter.Modifier.PARAMS){
if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
if (!may_fail)
Error_InvalidArguments (
loc, j, method, delegate_type,
Argument.FullDesc (a), pd.ParameterDesc (j));
return false;
}
if (chose_params_expanded)
parameter_type = TypeManager.GetElementType (parameter_type);
} else if (pm == Parameter.Modifier.ARGLIST){
continue;
} else {
//
// Check modifiers
//
if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
if (!may_fail)
Error_InvalidArguments (
loc, j, method, delegate_type,
Argument.FullDesc (a), pd.ParameterDesc (j));
return false;
}
}
//
// Check Type
//
if (!TypeManager.IsEqual (a.Type, parameter_type)){
Expression conv;
conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
if (conv == null) {
if (!may_fail)
Error_InvalidArguments (
loc, j, method, delegate_type,
Argument.FullDesc (a), pd.ParameterDesc (j));
return false;
}
//
// Update the argument with the implicit conversion
//
if (a_expr != conv)
a.Expr = conv;
}
if (parameter_type.IsPointer){
if (!ec.InUnsafe){
UnsafeError (loc);
return false;
}
}
Parameter.Modifier a_mod = a.GetParameterModifier () &
unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
Parameter.Modifier p_mod = pd.ParameterModifier (j) &
unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
if (a_mod != p_mod &&
pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
if (!may_fail) {
Report.Error (1502, loc,
"The best overloaded match for method '" + FullMethodDesc (method)+
"' has some invalid arguments");
Report.Error (1503, loc,
"Argument " + (j+1) +
": Cannot convert from '" + Argument.FullDesc (a)
+ "' to '" + pd.ParameterDesc (j) + "'");
}
return false;
}
}
return true;
}
public override Expression DoResolve (EmitContext ec)
{
//
// First, resolve the expression that is used to
// trigger the invocation
//
SimpleName sn = expr as SimpleName;
if (sn != null)
expr = sn.GetMethodGroup ();
expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
if (expr == null)
return null;
if (!(expr is MethodGroupExpr)) {
Type expr_type = expr.Type;
if (expr_type != null){
bool IsDelegate = TypeManager.IsDelegateType (expr_type);
if (IsDelegate)
return (new DelegateInvocation (
this.expr, Arguments, loc)).Resolve (ec);
}
}
if (!(expr is MethodGroupExpr)){
expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
return null;
}
//
// Next, evaluate all the expressions in the argument list
//
if (Arguments != null){
foreach (Argument a in Arguments){
if (!a.Resolve (ec, loc))
return null;
}
}
MethodGroupExpr mg = (MethodGroupExpr) expr;
method = OverloadResolve (ec, mg, Arguments, false, loc);
if (method == null)
return null;
MethodInfo mi = method as MethodInfo;
if (mi != null) {
type = TypeManager.TypeToCoreType (mi.ReturnType);
if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
return null;
}
Expression iexpr = mg.InstanceExpression;
if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
if (mg.IdenticalTypeName)
mg.InstanceExpression = null;
else {
MemberAccess.error176 (loc, mi.Name);
return null;
}
}
}
if (type.IsPointer){
if (!ec.InUnsafe){
UnsafeError (loc);
return null;
}
}
//
// Only base will allow this invocation to happen.
//
if (mg.IsBase && method.IsAbstract){
Report.Error (205, loc, "Cannot call an abstract base member: " +
FullMethodDesc (method));
return null;
}
if (method.Name == "Finalize" && Arguments == null) {
if (mg.IsBase)
Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
else
Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
return null;
}
if ((method.Attributes & MethodAttributes.SpecialName) != 0){
if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
return null;
}
}
if (mg.InstanceExpression != null)
mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
eclass = ExprClass.Value;
return this;
}
//
// Emits the list of arguments as an array
//
static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
{
ILGenerator ig = ec.ig;
int count = arguments.Count - idx;
Argument a = (Argument) arguments [idx];
Type t = a.Expr.Type;
IntConstant.EmitInt (ig, count);
ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
int top = arguments.Count;
for (int j = idx; j < top; j++){
a = (Argument) arguments [j];
ig.Emit (OpCodes.Dup);
IntConstant.EmitInt (ig, j - idx);
bool is_stobj, has_type_arg;
OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj, out has_type_arg);
if (is_stobj)
ig.Emit (OpCodes.Ldelema, t);
a.Emit (ec);
if (has_type_arg)
ig.Emit (op, t);
else
ig.Emit (op);
}
}
///
/// Emits a list of resolved Arguments that are in the arguments
/// ArrayList.
///
/// The MethodBase argument might be null if the
/// emission of the arguments is known not to contain
/// a `params' field (for example in constructors or other routines
/// that keep their arguments in this structure)
///
/// if `dup_args' is true, a copy of the arguments will be left
/// on the stack. If `dup_args' is true, you can specify `this_arg'
/// which will be duplicated before any other args. Only EmitCall
/// should be using this interface.
///
public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
{
ParameterData pd;
if (mb != null)
pd = TypeManager.GetParameterData (mb);
else
pd = null;
LocalTemporary [] temps = null;
if (dup_args)
temps = new LocalTemporary [arguments.Count];
//
// If we are calling a params method with no arguments, special case it
//
if (arguments == null){
if (pd != null && pd.Count > 0 &&
pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
ILGenerator ig = ec.ig;
IntConstant.EmitInt (ig, 0);
ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
}
return;
}
int top = arguments.Count;
for (int i = 0; i < top; i++){
Argument a = (Argument) arguments [i];
if (pd != null){
if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
//
// Special case if we are passing the same data as the
// params argument, do not put it in an array.
//
if (pd.ParameterType (i) == a.Type)
a.Emit (ec);
else
EmitParams (ec, i, arguments);
return;
}
}
a.Emit (ec);
if (dup_args) {
ec.ig.Emit (OpCodes.Dup);
(temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
}
}
if (dup_args) {
if (this_arg != null)
this_arg.Emit (ec);
for (int i = 0; i < top; i ++)
temps [i].Emit (ec);
}
if (pd != null && pd.Count > top &&
pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
ILGenerator ig = ec.ig;
IntConstant.EmitInt (ig, 0);
ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
}
}
static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
ArrayList arguments)
{
ParameterData pd = TypeManager.GetParameterData (mb);
if (arguments == null)
return new Type [0];
Argument a = (Argument) arguments [pd.Count - 1];
Arglist list = (Arglist) a.Expr;
return list.ArgumentTypes;
}
///
/// This checks the ConditionalAttribute on the method
///
static bool IsMethodExcluded (MethodBase method, EmitContext ec)
{
if (method.IsConstructor)
return false;
IMethodData md = TypeManager.GetMethod (method);
if (md != null)
return md.IsExcluded (ec);
// For some methods (generated by delegate class) GetMethod returns null
// because they are not included in builder_to_method table
if (method.DeclaringType is TypeBuilder)
return false;
return AttributeTester.IsConditionalMethodExcluded (method);
}
///
/// is_base tells whether we want to force the use of the `call'
/// opcode instead of using callvirt. Call is required to call
/// a specific method, while callvirt will always use the most
/// recent method in the vtable.
///
/// is_static tells whether this is an invocation on a static method
///
/// instance_expr is an expression that represents the instance
/// it must be non-null if is_static is false.
///
/// method is the method to invoke.
///
/// Arguments is the list of arguments to pass to the method or constructor.
///
public static void EmitCall (EmitContext ec, bool is_base,
bool is_static, Expression instance_expr,
MethodBase method, ArrayList Arguments, Location loc)
{
EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
}
// `dup_args' leaves an extra copy of the arguments on the stack
// `omit_args' does not leave any arguments at all.
// So, basically, you could make one call with `dup_args' set to true,
// and then another with `omit_args' set to true, and the two calls
// would have the same set of arguments. However, each argument would
// only have been evaluated once.
public static void EmitCall (EmitContext ec, bool is_base,
bool is_static, Expression instance_expr,
MethodBase method, ArrayList Arguments, Location loc,
bool dup_args, bool omit_args)
{
ILGenerator ig = ec.ig;
bool struct_call = false;
bool this_call = false;
LocalTemporary this_arg = null;
Type decl_type = method.DeclaringType;
if (!RootContext.StdLib) {
// Replace any calls to the system's System.Array type with calls to
// the newly created one.
if (method == TypeManager.system_int_array_get_length)
method = TypeManager.int_array_get_length;
else if (method == TypeManager.system_int_array_get_rank)
method = TypeManager.int_array_get_rank;
else if (method == TypeManager.system_object_array_clone)
method = TypeManager.object_array_clone;
else if (method == TypeManager.system_int_array_get_length_int)
method = TypeManager.int_array_get_length_int;
else if (method == TypeManager.system_int_array_get_lower_bound_int)
method = TypeManager.int_array_get_lower_bound_int;
else if (method == TypeManager.system_int_array_get_upper_bound_int)
method = TypeManager.int_array_get_upper_bound_int;
else if (method == TypeManager.system_void_array_copyto_array_int)
method = TypeManager.void_array_copyto_array_int;
}
if (ec.TestObsoleteMethodUsage) {
//
// This checks ObsoleteAttribute on the method and on the declaring type
//
ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
if (oa != null)
AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
if (oa != null) {
AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
}
}
if (IsMethodExcluded (method, ec))
return;
if (!is_static){
this_call = instance_expr == null;
if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
struct_call = true;
//
// If this is ourselves, push "this"
//
if (!omit_args) {
Type t = null;
if (this_call) {
ig.Emit (OpCodes.Ldarg_0);
t = decl_type;
} else {
Type iexpr_type = instance_expr.Type;
//
// Push the instance expression
//
if (TypeManager.IsValueType (iexpr_type)) {
//
// Special case: calls to a function declared in a
// reference-type with a value-type argument need
// to have their value boxed.
if (decl_type.IsValueType ||
iexpr_type.IsGenericParameter) {
//
// If the expression implements IMemoryLocation, then
// we can optimize and use AddressOf on the
// return.
//
// If not we have to use some temporary storage for
// it.
if (instance_expr is IMemoryLocation) {
((IMemoryLocation)instance_expr).
AddressOf (ec, AddressOp.LoadStore);
} else {
LocalTemporary temp = new LocalTemporary (ec, iexpr_type);
instance_expr.Emit (ec);
temp.Store (ec);
temp.AddressOf (ec, AddressOp.Load);
}
// avoid the overhead of doing this all the time.
if (dup_args)
t = TypeManager.GetReferenceType (iexpr_type);
} else {
instance_expr.Emit (ec);
ig.Emit (OpCodes.Box, instance_expr.Type);
t = TypeManager.object_type;
}
} else {
instance_expr.Emit (ec);
t = instance_expr.Type;
}
}
if (dup_args) {
this_arg = new LocalTemporary (ec, t);
ig.Emit (OpCodes.Dup);
this_arg.Store (ec);
}
}
}
if (!omit_args)
EmitArguments (ec, method, Arguments, dup_args, this_arg);
if ((instance_expr != null) && (instance_expr.Type.IsGenericParameter))
ig.Emit (OpCodes.Constrained, instance_expr.Type);
OpCode call_op;
if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
call_op = OpCodes.Call;
else
call_op = OpCodes.Callvirt;
if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
return;
}
//
// If you have:
// this.DoFoo ();
// and DoFoo is not virtual, you can omit the callvirt,
// because you don't need the null checking behavior.
//
if (method is MethodInfo)
ig.Emit (call_op, (MethodInfo) method);
else
ig.Emit (call_op, (ConstructorInfo) method);
}
public override void Emit (EmitContext ec)
{
MethodGroupExpr mg = (MethodGroupExpr) this.expr;
EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
}
public override void EmitStatement (EmitContext ec)
{
Emit (ec);
//
// Pop the return value if there is one
//
if (method is MethodInfo){
Type ret = ((MethodInfo)method).ReturnType;
if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
ec.ig.Emit (OpCodes.Pop);
}
}
}
public class InvocationOrCast : ExpressionStatement
{
Expression expr;
Expression argument;
public InvocationOrCast (Expression expr, Expression argument, Location loc)
{
this.expr = expr;
this.argument = argument;
this.loc = loc;
}
public override Expression DoResolve (EmitContext ec)
{
//
// First try to resolve it as a cast.
//
TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
if ((te != null) && (te.eclass == ExprClass.Type)) {
Cast cast = new Cast (te, argument, loc);
return cast.Resolve (ec);
}
//
// This can either be a type or a delegate invocation.
// Let's just resolve it and see what we'll get.
//
expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
if (expr == null)
return null;
//
// Ok, so it's a Cast.
//
if (expr.eclass == ExprClass.Type) {
Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
return cast.Resolve (ec);
}
//
// It's a delegate invocation.
//
if (!TypeManager.IsDelegateType (expr.Type)) {
Error (149, "Method name expected");
return null;
}
ArrayList args = new ArrayList ();
args.Add (new Argument (argument, Argument.AType.Expression));
DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
return invocation.Resolve (ec);
}
void error201 ()
{
Error (201, "Only assignment, call, increment, decrement and new object " +
"expressions can be used as a statement");
}
public override ExpressionStatement ResolveStatement (EmitContext ec)
{
//
// First try to resolve it as a cast.
//
TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
if ((te != null) && (te.eclass == ExprClass.Type)) {
error201 ();
return null;
}
//
// This can either be a type or a delegate invocation.
// Let's just resolve it and see what we'll get.
//
expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
if ((expr == null) || (expr.eclass == ExprClass.Type)) {
error201 ();
return null;
}
//
// It's a delegate invocation.
//
if (!TypeManager.IsDelegateType (expr.Type)) {
Error (149, "Method name expected");
return null;
}
ArrayList args = new ArrayList ();
args.Add (new Argument (argument, Argument.AType.Expression));
DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
return invocation.ResolveStatement (ec);
}
public override void Emit (EmitContext ec)
{
throw new Exception ("Cannot happen");
}
public override void EmitStatement (EmitContext ec)
{
throw new Exception ("Cannot happen");
}
}
//
// This class is used to "disable" the code generation for the
// temporary variable when initializing value types.
//
class EmptyAddressOf : EmptyExpression, IMemoryLocation {
public void AddressOf (EmitContext ec, AddressOp Mode)
{
// nothing
}
}
///
/// Implements the new expression
///
public class New : ExpressionStatement, IMemoryLocation {
public readonly ArrayList Arguments;
//
// During bootstrap, it contains the RequestedType,
// but if `type' is not null, it *might* contain a NewDelegate
// (because of field multi-initialization)
//
public Expression RequestedType;
MethodBase method = null;
//
// If set, the new expression is for a value_target, and
// we will not leave anything on the stack.
//
Expression value_target;
bool value_target_set = false;
bool is_type_parameter = false;
public New (Expression requested_type, ArrayList arguments, Location l)
{
RequestedType = requested_type;
Arguments = arguments;
loc = l;
}
public bool SetValueTypeVariable (Expression value)
{
value_target = value;
value_target_set = true;
if (!(value_target is IMemoryLocation)){
Error_UnexpectedKind ("variable", loc);
return false;
}
return true;
}
//
// This function is used to disable the following code sequence for
// value type initialization:
//
// AddressOf (temporary)
// Construct/Init
// LoadTemporary
//
// Instead the provide will have provided us with the address on the
// stack to store the results.
//
static Expression MyEmptyExpression;
public void DisableTemporaryValueType ()
{
if (MyEmptyExpression == null)
MyEmptyExpression = new EmptyAddressOf ();
//
// To enable this, look into:
// test-34 and test-89 and self bootstrapping.
//
// For instance, we can avoid a copy by using `newobj'
// instead of Call + Push-temp on value types.
// value_target = MyEmptyExpression;
}
///
/// Converts complex core type syntax like 'new int ()' to simple constant
///
Expression Constantify (Type t)
{
if (t == TypeManager.int32_type)
return new IntConstant (0);
if (t == TypeManager.uint32_type)
return new UIntConstant (0);
if (t == TypeManager.int64_type)
return new LongConstant (0);
if (t == TypeManager.uint64_type)
return new ULongConstant (0);
if (t == TypeManager.float_type)
return new FloatConstant (0);
if (t == TypeManager.double_type)
return new DoubleConstant (0);
if (t == TypeManager.short_type)
return new ShortConstant (0);
if (t == TypeManager.ushort_type)
return new UShortConstant (0);
if (t == TypeManager.sbyte_type)
return new SByteConstant (0);
if (t == TypeManager.byte_type)
return new ByteConstant (0);
if (t == TypeManager.char_type)
return new CharConstant ('\0');
if (t == TypeManager.bool_type)
return new BoolConstant (false);
if (t == TypeManager.decimal_type)
return new DecimalConstant (0);
return null;
}
public override Expression DoResolve (EmitContext ec)
{
//
// The New DoResolve might be called twice when initializing field
// expressions (see EmitFieldInitializers, the call to
// GetInitializerExpression will perform a resolve on the expression,
// and later the assign will trigger another resolution
//
// This leads to bugs (#37014)
//
if (type != null){
if (RequestedType is NewDelegate)
return RequestedType;
return this;
}
TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec);
if (texpr == null)
return null;
if (Arguments == null) {
Expression c = Constantify (type);
if (c != null)
return c;
}
type = texpr.Type;
if (type == null)
return null;
CheckObsoleteAttribute (type);
bool IsDelegate = TypeManager.IsDelegateType (type);
if (IsDelegate){
RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
if (RequestedType != null)
if (!(RequestedType is DelegateCreation))
throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
return RequestedType;
}
if (type.IsGenericParameter) {
if (!TypeManager.HasConstructorConstraint (type)) {
Error (304, String.Format (
"Cannot create an instance of the " +
"variable type '{0}' because it " +
"doesn't have the new() constraint",
type));
return null;
}
if ((Arguments != null) && (Arguments.Count != 0)) {
Error (417, String.Format (
"`{0}': cannot provide arguments " +
"when creating an instance of a " +
"variable type.", type));
return null;
}
is_type_parameter = true;
eclass = ExprClass.Value;
return this;
}
if (type.IsInterface || type.IsAbstract){
Error (144, "It is not possible to create instances of interfaces or abstract classes");
return null;
}
if (type.IsAbstract && type.IsSealed) {
Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
return null;
}
bool is_struct = type.IsValueType;
eclass = ExprClass.Value;
//
// SRE returns a match for .ctor () on structs (the object constructor),
// so we have to manually ignore it.
//
if (is_struct && Arguments == null)
return this;
Expression ml;
ml = MemberLookupFinal (ec, type, type, ".ctor",
// For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
MemberTypes.Constructor,
AllBindingFlags | BindingFlags.DeclaredOnly, loc);
if (ml == null)
return null;
if (! (ml is MethodGroupExpr)){
if (!is_struct){
ml.Error_UnexpectedKind ("method group", loc);
return null;
}
}
if (ml != null) {
if (Arguments != null){
foreach (Argument a in Arguments){
if (!a.Resolve (ec, loc))
return null;
}
}
method = Invocation.OverloadResolve (
ec, (MethodGroupExpr) ml, Arguments, true, loc);
}
if (method == null) {
if (almostMatchedMembers.Count != 0) {
MemberLookupFailed (ec, type, type, ".ctor", null, true, 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",
TypeManager.CSharpName (type)));
return null;
}
}
return this;
}
bool DoEmitTypeParameter (EmitContext ec)
{
ILGenerator ig = ec.ig;
ig.Emit (OpCodes.Ldtoken, type);
ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
ig.Emit (OpCodes.Call, TypeManager.activator_create_instance);
ig.Emit (OpCodes.Unbox_Any, type);
return true;
}
//
// This DoEmit can be invoked in two contexts:
// * As a mechanism that will leave a value on the stack (new object)
// * As one that wont (init struct)
//
// You can control whether a value is required on the stack by passing
// need_value_on_stack. The code *might* leave a value on the stack
// so it must be popped manually
//
// If we are dealing with a ValueType, we have a few
// situations to deal with:
//
// * The target is a ValueType, and we have been provided
// the instance (this is easy, we are being assigned).
//
// * The target of New is being passed as an argument,
// to a boxing operation or a function that takes a
// ValueType.
//
// In this case, we need to create a temporary variable
// that is the argument of New.
//
// Returns whether a value is left on the stack
//
bool DoEmit (EmitContext ec, bool need_value_on_stack)
{
bool is_value_type = TypeManager.IsValueType (type);
ILGenerator ig = ec.ig;
if (is_value_type){
IMemoryLocation ml;
// Allow DoEmit() to be called multiple times.
// We need to create a new LocalTemporary each time since
// you can't share LocalBuilders among ILGeneators.
if (!value_target_set)
value_target = new LocalTemporary (ec, type);
ml = (IMemoryLocation) value_target;
ml.AddressOf (ec, AddressOp.Store);
}
if (method != null)
Invocation.EmitArguments (ec, method, Arguments, false, null);
if (is_value_type){
if (method == null)
ig.Emit (OpCodes.Initobj, type);
else
ig.Emit (OpCodes.Call, (ConstructorInfo) method);
if (need_value_on_stack){
value_target.Emit (ec);
return true;
}
return false;
} else {
ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
return true;
}
}
public override void Emit (EmitContext ec)
{
if (is_type_parameter)
DoEmitTypeParameter (ec);
else
DoEmit (ec, true);
}
public override void EmitStatement (EmitContext ec)
{
if (is_type_parameter)
throw new InvalidOperationException ();
if (DoEmit (ec, false))
ec.ig.Emit (OpCodes.Pop);
}
public void AddressOf (EmitContext ec, AddressOp Mode)
{
if (is_type_parameter)
throw new InvalidOperationException ();
if (!type.IsValueType){
//
// We throw an exception. So far, I believe we only need to support
// value types:
// foreach (int j in new StructType ())
// see bug 42390
//
throw new Exception ("AddressOf should not be used for classes");
}
if (!value_target_set)
value_target = new LocalTemporary (ec, type);
IMemoryLocation ml = (IMemoryLocation) value_target;
ml.AddressOf (ec, AddressOp.Store);
if (method != null)
Invocation.EmitArguments (ec, method, Arguments, false, null);
if (method == null)
ec.ig.Emit (OpCodes.Initobj, type);
else
ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
((IMemoryLocation) value_target).AddressOf (ec, Mode);
}
}
///
/// 14.5.10.2: Represents an array creation expression.
///
///
///
/// There are two possible scenarios here: one is an array creation
/// expression that specifies the dimensions and optionally the
/// initialization data and the other which does not need dimensions
/// specified but where initialization data is mandatory.
///
public class ArrayCreation : Expression {
Expression requested_base_type;
ArrayList initializers;
//
// The list of Argument types.
// This is used to construct the `newarray' or constructor signature
//
ArrayList arguments;
//
// Method used to create the array object.
//
MethodBase new_method = null;
Type array_element_type;
Type underlying_type;
bool is_one_dimensional = false;
bool is_builtin_type = false;
bool expect_initializers = false;
int num_arguments = 0;
int dimensions = 0;
string rank;
ArrayList array_data;
Hashtable bounds;
//
// The number of array initializers that we can handle
// via the InitializeArray method - through EmitStaticInitializers
//
int num_automatic_initializers;
const int max_automatic_initializers = 6;
public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
{
this.requested_base_type = requested_base_type;
this.initializers = initializers;
this.rank = rank;
loc = l;
arguments = new ArrayList ();
foreach (Expression e in exprs) {
arguments.Add (new Argument (e, Argument.AType.Expression));
num_arguments++;
}
}
public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
{
this.requested_base_type = requested_base_type;
this.initializers = initializers;
this.rank = rank;
loc = l;
//this.rank = rank.Substring (0, rank.LastIndexOf ('['));
//
//string tmp = rank.Substring (rank.LastIndexOf ('['));
//
//dimensions = tmp.Length - 1;
expect_initializers = true;
}
public Expression FormArrayType (Expression base_type, int idx_count, string rank)
{
StringBuilder sb = new StringBuilder (rank);
sb.Append ("[");
for (int i = 1; i < idx_count; i++)
sb.Append (",");
sb.Append ("]");
return new ComposedCast (base_type, sb.ToString (), loc);
}
void Error_IncorrectArrayInitializer ()
{
Error (178, "Incorrectly structured array initializer");
}
public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
{
if (specified_dims) {
Argument a = (Argument) arguments [idx];
if (!a.Resolve (ec, loc))
return false;
if (!(a.Expr is Constant)) {
Error (150, "A constant value is expected");
return false;
}
int value = (int) ((Constant) a.Expr).GetValue ();
if (value != probe.Count) {
Error_IncorrectArrayInitializer ();
return false;
}
bounds [idx] = value;
}
int child_bounds = -1;
foreach (object o in probe) {
if (o is ArrayList) {
int current_bounds = ((ArrayList) o).Count;
if (child_bounds == -1)
child_bounds = current_bounds;
else if (child_bounds != current_bounds){
Error_IncorrectArrayInitializer ();
return false;
}
if (specified_dims && (idx + 1 >= arguments.Count)){
Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
return false;
}
bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
if (!ret)
return false;
} else {
if (child_bounds != -1){
Error_IncorrectArrayInitializer ();
return false;
}
Expression tmp = (Expression) o;
tmp = tmp.Resolve (ec);
if (tmp == null)
return false;
// Console.WriteLine ("I got: " + tmp);
// Handle initialization from vars, fields etc.
Expression conv = Convert.ImplicitConversionRequired (
ec, tmp, underlying_type, loc);
if (conv == null)
return false;
if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
// These are subclasses of Constant that can appear as elements of an
// array that cannot be statically initialized (with num_automatic_initializers
// > max_automatic_initializers), so num_automatic_initializers should be left as zero.
array_data.Add (conv);
} else if (conv is Constant) {
// These are the types of Constant that can appear in arrays that can be
// statically allocated.
array_data.Add (conv);
num_automatic_initializers++;
} else
array_data.Add (conv);
}
}
return true;
}
public void UpdateIndices (EmitContext ec)
{
int i = 0;
for (ArrayList probe = initializers; probe != null;) {
if (probe.Count > 0 && probe [0] is ArrayList) {
Expression e = new IntConstant (probe.Count);
arguments.Add (new Argument (e, Argument.AType.Expression));
bounds [i++] = probe.Count;
probe = (ArrayList) probe [0];
} else {
Expression e = new IntConstant (probe.Count);
arguments.Add (new Argument (e, Argument.AType.Expression));
bounds [i++] = probe.Count;
probe = null;
}
}
}
public bool ValidateInitializers (EmitContext ec, Type array_type)
{
if (initializers == null) {
if (expect_initializers)
return false;
else
return true;
}
if (underlying_type == null)
return false;
//
// We use this to store all the date values in the order in which we
// will need to store them in the byte blob later
//
array_data = new ArrayList ();
bounds = new Hashtable ();
bool ret;
if (arguments != null) {
ret = CheckIndices (ec, initializers, 0, true);
return ret;
} else {
arguments = new ArrayList ();
ret = CheckIndices (ec, initializers, 0, false);
if (!ret)
return false;
UpdateIndices (ec);
if (arguments.Count != dimensions) {
Error_IncorrectArrayInitializer ();
return false;
}
return ret;
}
}
//
// Converts `source' to an int, uint, long or ulong.
//
Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
{
Expression target;
bool old_checked = ec.CheckState;
ec.CheckState = true;
target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
if (target == null){
target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
if (target == null){
target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
if (target == null){
target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
if (target == null)
Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
}
}
}
ec.CheckState = old_checked;
//
// Only positive constants are allowed at compile time
//
if (target is Constant){
if (target is IntConstant){
if (((IntConstant) target).Value < 0){
Expression.Error_NegativeArrayIndex (loc);
return null;
}
}
if (target is LongConstant){
if (((LongConstant) target).Value < 0){
Expression.Error_NegativeArrayIndex (loc);
return null;
}
}
}
return target;
}
//
// Creates the type of the array
//
bool LookupType (EmitContext ec)
{
StringBuilder array_qualifier = new StringBuilder (rank);
//
// `In the first form allocates an array instace of the type that results
// from deleting each of the individual expression from the expression list'
//
if (num_arguments > 0) {
array_qualifier.Append ("[");
for (int i = num_arguments-1; i > 0; i--)
array_qualifier.Append (",");
array_qualifier.Append ("]");
}
//
// Lookup the type
//
TypeExpr array_type_expr;
array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec);
if (array_type_expr == null)
return false;
type = array_type_expr.Type;
if (!type.IsArray) {
Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
return false;
}
underlying_type = TypeManager.GetElementType (type);
dimensions = type.GetArrayRank ();
return true;
}
public override Expression DoResolve (EmitContext ec)
{
int arg_count;
if (!LookupType (ec))
return null;
//
// First step is to validate the initializers and fill
// in any missing bits
//
if (!ValidateInitializers (ec, type))
return null;
if (arguments == null)
arg_count = 0;
else {
arg_count = arguments.Count;
foreach (Argument a in arguments){
if (!a.Resolve (ec, loc))
return null;
Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
if (real_arg == null)
return null;
a.Expr = real_arg;
}
}
array_element_type = TypeManager.GetElementType (type);
if (array_element_type.IsAbstract && array_element_type.IsSealed) {
Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
return null;
}
if (arg_count == 1) {
is_one_dimensional = true;
eclass = ExprClass.Value;
return this;
}
is_builtin_type = TypeManager.IsBuiltinType (type);
if (is_builtin_type) {
Expression ml;
ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
AllBindingFlags, loc);
if (!(ml is MethodGroupExpr)) {
ml.Error_UnexpectedKind ("method group", loc);
return null;
}
if (ml == null) {
Error (-6, "New invocation: Can not find a constructor for " +
"this argument list");
return null;
}
new_method = Invocation.OverloadResolve (
ec, (MethodGroupExpr) ml, arguments, false, loc);
if (new_method == null) {
Error (-6, "New invocation: Can not find a constructor for " +
"this argument list");
return null;
}
eclass = ExprClass.Value;
return this;
} else {
ModuleBuilder mb = CodeGen.Module.Builder;
ArrayList args = new ArrayList ();
if (arguments != null) {
for (int i = 0; i < arg_count; i++)
args.Add (TypeManager.int32_type);
}
Type [] arg_types = null;
if (args.Count > 0)
arg_types = new Type [args.Count];
args.CopyTo (arg_types, 0);
new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
arg_types);
if (new_method == null) {
Error (-6, "New invocation: Can not find a constructor for " +
"this argument list");
return null;
}
eclass = ExprClass.Value;
return this;
}
}
public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
{
int factor;
byte [] data;
byte [] element;
int count = array_data.Count;
if (underlying_type.IsEnum)
underlying_type = TypeManager.EnumToUnderlying (underlying_type);
factor = GetTypeSize (underlying_type);
if (factor == 0)
throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
data = new byte [(count * factor + 4) & ~3];
int idx = 0;
for (int i = 0; i < count; ++i) {
object v = array_data [i];
if (v is EnumConstant)
v = ((EnumConstant) v).Child;
if (v is Constant && !(v is StringConstant))
v = ((Constant) v).GetValue ();
else {
idx += factor;
continue;
}
if (underlying_type == TypeManager.int64_type){
if (!(v is Expression)){
long val = (long) v;
for (int j = 0; j < factor; ++j) {
data [idx + j] = (byte) (val & 0xFF);
val = (val >> 8);
}
}
} else if (underlying_type == TypeManager.uint64_type){
if (!(v is Expression)){
ulong val = (ulong) v;
for (int j = 0; j < factor; ++j) {
data [idx + j] = (byte) (val & 0xFF);
val = (val >> 8);
}
}
} else if (underlying_type == TypeManager.float_type) {
if (!(v is Expression)){
element = BitConverter.GetBytes ((float) v);
for (int j = 0; j < factor; ++j)
data [idx + j] = element [j];
}
} else if (underlying_type == TypeManager.double_type) {
if (!(v is Expression)){
element = BitConverter.GetBytes ((double) v);
for (int j = 0; j < factor; ++j)
data [idx + j] = element [j];
}
} else if (underlying_type == TypeManager.char_type){
if (!(v is Expression)){
int val = (int) ((char) v);
data [idx] = (byte) (val & 0xff);
data [idx+1] = (byte) (val >> 8);
}
} else if (underlying_type == TypeManager.short_type){
if (!(v is Expression)){
int val = (int) ((short) v);
data [idx] = (byte) (val & 0xff);
data [idx+1] = (byte) (val >> 8);
}
} else if (underlying_type == TypeManager.ushort_type){
if (!(v is Expression)){
int val = (int) ((ushort) v);
data [idx] = (byte) (val & 0xff);
data [idx+1] = (byte) (val >> 8);
}
} else if (underlying_type == TypeManager.int32_type) {
if (!(v is Expression)){
int val = (int) v;
data [idx] = (byte) (val & 0xff);
data [idx+1] = (byte) ((val >> 8) & 0xff);
data [idx+2] = (byte) ((val >> 16) & 0xff);
data [idx+3] = (byte) (val >> 24);
}
} else if (underlying_type == TypeManager.uint32_type) {
if (!(v is Expression)){
uint val = (uint) v;
data [idx] = (byte) (val & 0xff);
data [idx+1] = (byte) ((val >> 8) & 0xff);
data [idx+2] = (byte) ((val >> 16) & 0xff);
data [idx+3] = (byte) (val >> 24);
}
} else if (underlying_type == TypeManager.sbyte_type) {
if (!(v is Expression)){
sbyte val = (sbyte) v;
data [idx] = (byte) val;
}
} else if (underlying_type == TypeManager.byte_type) {
if (!(v is Expression)){
byte val = (byte) v;
data [idx] = (byte) val;
}
} else if (underlying_type == TypeManager.bool_type) {
if (!(v is Expression)){
bool val = (bool) v;
data [idx] = (byte) (val ? 1 : 0);
}
} else if (underlying_type == TypeManager.decimal_type){
if (!(v is Expression)){
int [] bits = Decimal.GetBits ((decimal) v);
int p = idx;
// FIXME: For some reason, this doesn't work on the MS runtime.
int [] nbits = new int [4];
nbits [0] = bits [3];
nbits [1] = bits [2];
nbits [2] = bits [0];
nbits [3] = bits [1];
for (int j = 0; j < 4; j++){
data [p++] = (byte) (nbits [j] & 0xff);
data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
data [p++] = (byte) (nbits [j] >> 24);
}
}
} else
throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
idx += factor;
}
return data;
}
//
// Emits the initializers for the array
//
void EmitStaticInitializers (EmitContext ec)
{
//
// First, the static data
//
FieldBuilder fb;
ILGenerator ig = ec.ig;
byte [] data = MakeByteBlob (array_data, underlying_type, loc);
fb = RootContext.MakeStaticData (data);
ig.Emit (OpCodes.Dup);
ig.Emit (OpCodes.Ldtoken, fb);
ig.Emit (OpCodes.Call,
TypeManager.void_initializearray_array_fieldhandle);
}
//
// Emits pieces of the array that can not be computed at compile
// time (variables and string locations).
//
// This always expect the top value on the stack to be the array
//
void EmitDynamicInitializers (EmitContext ec)
{
ILGenerator ig = ec.ig;
int dims = bounds.Count;
int [] current_pos = new int [dims];
int top = array_data.Count;
MethodInfo set = null;
if (dims != 1){
Type [] args;
ModuleBuilder mb = null;
mb = CodeGen.Module.Builder;
args = new Type [dims + 1];
int j;
for (j = 0; j < dims; j++)
args [j] = TypeManager.int32_type;
args [j] = array_element_type;
set = mb.GetArrayMethod (
type, "Set",
CallingConventions.HasThis | CallingConventions.Standard,
TypeManager.void_type, args);
}
for (int i = 0; i < top; i++){
Expression e = null;
if (array_data [i] is Expression)
e = (Expression) array_data [i];
if (e != null) {
//
// Basically we do this for string literals and
// other non-literal expressions
//
if (e is EnumConstant){
e = ((EnumConstant) e).Child;
}
if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
num_automatic_initializers <= max_automatic_initializers) {
Type etype = e.Type;
ig.Emit (OpCodes.Dup);
for (int idx = 0; idx < dims; idx++)
IntConstant.EmitInt (ig, current_pos [idx]);
//
// If we are dealing with a struct, get the
// address of it, so we can store it.
//
if ((dims == 1) && etype.IsValueType &&
(!TypeManager.IsBuiltinOrEnum (etype) ||
etype == TypeManager.decimal_type)) {
if (e is New){
New n = (New) e;
//
// Let new know that we are providing
// the address where to store the results
//
n.DisableTemporaryValueType ();
}
ig.Emit (OpCodes.Ldelema, etype);
}
e.Emit (ec);
if (dims == 1) {
bool is_stobj, has_type_arg;
OpCode op = ArrayAccess.GetStoreOpcode (
etype, out is_stobj,
out has_type_arg);
if (is_stobj)
ig.Emit (OpCodes.Stobj, etype);
else if (has_type_arg)
ig.Emit (op, etype);
else
ig.Emit (op);
} else
ig.Emit (OpCodes.Call, set);
}
}
//
// Advance counter
//
for (int j = dims - 1; j >= 0; j--){
current_pos [j]++;
if (current_pos [j] < (int) bounds [j])
break;
current_pos [j] = 0;
}
}
}
void EmitArrayArguments (EmitContext ec)
{
ILGenerator ig = ec.ig;
foreach (Argument a in arguments) {
Type atype = a.Type;
a.Emit (ec);
if (atype == TypeManager.uint64_type)
ig.Emit (OpCodes.Conv_Ovf_U4);
else if (atype == TypeManager.int64_type)
ig.Emit (OpCodes.Conv_Ovf_I4);
}
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
EmitArrayArguments (ec);
if (is_one_dimensional)
ig.Emit (OpCodes.Newarr, array_element_type);
else {
if (is_builtin_type)
ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
else
ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
}
if (initializers != null){
//
// FIXME: Set this variable correctly.
//
bool dynamic_initializers = true;
// This will never be true for array types that cannot be statically
// initialized. num_automatic_initializers will always be zero. See
// CheckIndices.
if (num_automatic_initializers > max_automatic_initializers)
EmitStaticInitializers (ec);
if (dynamic_initializers)
EmitDynamicInitializers (ec);
}
}
public object EncodeAsAttribute ()
{
if (!is_one_dimensional){
Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
return null;
}
if (array_data == null){
Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
return null;
}
object [] ret = new object [array_data.Count];
int i = 0;
foreach (Expression e in array_data){
object v;
if (e is NullLiteral)
v = null;
else {
if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
return null;
}
ret [i++] = v;
}
return ret;
}
}
///
/// Represents the `this' construct
///
public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
Block block;
VariableInfo variable_info;
public This (Block block, Location loc)
{
this.loc = loc;
this.block = block;
}
public This (Location loc)
{
this.loc = loc;
}
public VariableInfo VariableInfo {
get { return variable_info; }
}
public bool VerifyFixed (bool is_expression)
{
if ((variable_info == null) || (variable_info.LocalInfo == null))
return false;
else
return variable_info.LocalInfo.IsFixed;
}
public bool ResolveBase (EmitContext ec)
{
eclass = ExprClass.Variable;
if (ec.TypeContainer.CurrentType != null)
type = ec.TypeContainer.CurrentType;
else
type = ec.ContainerType;
if (ec.IsStatic) {
Error (26, "Keyword this not valid in static code");
return false;
}
if ((block != null) && (block.ThisVariable != null))
variable_info = block.ThisVariable.VariableInfo;
if (ec.CurrentAnonymousMethod != null)
ec.CaptureThis ();
return true;
}
public override Expression DoResolve (EmitContext ec)
{
if (!ResolveBase (ec))
return null;
if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
Error (188, "The this object cannot be used before all " +
"of its fields are assigned to");
variable_info.SetAssigned (ec);
return this;
}
if (ec.IsFieldInitializer) {
Error (27, "Keyword `this' can't be used outside a constructor, " +
"a method or a property.");
return null;
}
return this;
}
override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
if (!ResolveBase (ec))
return null;
if (variable_info != null)
variable_info.SetAssigned (ec);
if (ec.TypeContainer is Class){
Error (1604, "Cannot assign to `this'");
return null;
}
return this;
}
public void Emit (EmitContext ec, bool leave_copy)
{
Emit (ec);
if (leave_copy)
ec.ig.Emit (OpCodes.Dup);
}
public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
{
ILGenerator ig = ec.ig;
if (ec.TypeContainer is Struct){
ec.EmitThis ();
source.Emit (ec);
if (leave_copy)
ec.ig.Emit (OpCodes.Dup);
ig.Emit (OpCodes.Stobj, type);
} else {
throw new Exception ("how did you get here");
}
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
ec.EmitThis ();
if (ec.TypeContainer is Struct)
ig.Emit (OpCodes.Ldobj, type);
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
ec.EmitThis ();
// FIMXE
// FIGURE OUT WHY LDARG_S does not work
//
// consider: struct X { int val; int P { set { val = value; }}}
//
// Yes, this looks very bad. Look at `NOTAS' for
// an explanation.
// ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
}
}
///
/// Represents the `__arglist' construct
///
public class ArglistAccess : Expression
{
public ArglistAccess (Location loc)
{
this.loc = loc;
}
public bool ResolveBase (EmitContext ec)
{
eclass = ExprClass.Variable;
type = TypeManager.runtime_argument_handle_type;
return true;
}
public override Expression DoResolve (EmitContext ec)
{
if (!ResolveBase (ec))
return null;
if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
Error (190, "The __arglist construct is valid only within " +
"a variable argument method.");
return null;
}
return this;
}
public override void Emit (EmitContext ec)
{
ec.ig.Emit (OpCodes.Arglist);
}
}
///
/// Represents the `__arglist (....)' construct
///
public class Arglist : Expression
{
public readonly Argument[] Arguments;
public Arglist (Argument[] args, Location l)
{
Arguments = args;
loc = l;
}
public Type[] ArgumentTypes {
get {
Type[] retval = new Type [Arguments.Length];
for (int i = 0; i < Arguments.Length; i++)
retval [i] = Arguments [i].Type;
return retval;
}
}
public override Expression DoResolve (EmitContext ec)
{
eclass = ExprClass.Variable;
type = TypeManager.runtime_argument_handle_type;
foreach (Argument arg in Arguments) {
if (!arg.Resolve (ec, loc))
return null;
}
return this;
}
public override void Emit (EmitContext ec)
{
foreach (Argument arg in Arguments)
arg.Emit (ec);
}
}
//
// This produces the value that renders an instance, used by the iterators code
//
public class ProxyInstance : Expression, IMemoryLocation {
public override Expression DoResolve (EmitContext ec)
{
eclass = ExprClass.Variable;
type = ec.ContainerType;
return this;
}
public override void Emit (EmitContext ec)
{
ec.ig.Emit (OpCodes.Ldarg_0);
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
ec.ig.Emit (OpCodes.Ldarg_0);
}
}
///
/// Implements the typeof operator
///
public class TypeOf : Expression {
public Expression QueriedType;
protected Type typearg;
public TypeOf (Expression queried_type, Location l)
{
QueriedType = queried_type;
loc = l;
}
public override Expression DoResolve (EmitContext ec)
{
TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
if (texpr == null)
return null;
typearg = texpr.Type;
if (typearg == TypeManager.void_type) {
Error (673, "System.Void cannot be used from C# - " +
"use typeof (void) to get the void type object");
return null;
}
if (typearg.IsPointer && !ec.InUnsafe){
UnsafeError (loc);
return null;
}
CheckObsoleteAttribute (typearg);
type = TypeManager.type_type;
eclass = ExprClass.Type;
return this;
}
public override void Emit (EmitContext ec)
{
ec.ig.Emit (OpCodes.Ldtoken, typearg);
ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
}
public Type TypeArg {
get { return typearg; }
}
}
///
/// Implements the `typeof (void)' operator
///
public class TypeOfVoid : TypeOf {
public TypeOfVoid (Location l) : base (null, l)
{
loc = l;
}
public override Expression DoResolve (EmitContext ec)
{
type = TypeManager.type_type;
typearg = TypeManager.void_type;
eclass = ExprClass.Type;
return this;
}
}
///
/// Implements the sizeof expression
///
public class SizeOf : Expression {
public Expression QueriedType;
Type type_queried;
public SizeOf (Expression queried_type, Location l)
{
this.QueriedType = queried_type;
loc = l;
}
public override Expression DoResolve (EmitContext ec)
{
TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
if (texpr == null)
return null;
if (texpr is TypeParameterExpr){
((TypeParameterExpr)texpr).Error_CannotUseAsUnmanagedType (loc);
return null;
}
type_queried = texpr.Type;
int size_of = GetTypeSize (type_queried);
if (size_of > 0) {
return new IntConstant (size_of);
}
if (!ec.InUnsafe) {
Report.Error (233, loc, "'{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
TypeManager.CSharpName (type_queried));
return null;
}
CheckObsoleteAttribute (type_queried);
if (!TypeManager.IsUnmanagedType (type_queried)){
Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
return null;
}
type = TypeManager.int32_type;
eclass = ExprClass.Value;
return this;
}
public override void Emit (EmitContext ec)
{
int size = GetTypeSize (type_queried);
if (size == 0)
ec.ig.Emit (OpCodes.Sizeof, type_queried);
else
IntConstant.EmitInt (ec.ig, size);
}
}
///
/// Implements the member access expression
///
public class MemberAccess : Expression {
public string Identifier;
protected Expression expr;
protected TypeArguments args;
public MemberAccess (Expression expr, string id, Location l)
{
this.expr = expr;
Identifier = id;
loc = l;
}
public MemberAccess (Expression expr, string id, TypeArguments args,
Location l)
: this (expr, id, l)
{
this.args = args;
}
public Expression Expr {
get {
return expr;
}
}
public static void error176 (Location loc, string name)
{
Report.Error (176, loc, "Static member `" +
name + "' cannot be accessed " +
"with an instance reference, qualify with a " +
"type name instead");
}
public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
{
SimpleName sn = left_original as SimpleName;
return sn != null && sn.IdenticalNameAndTypeName (ec, left, loc);
}
// 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)
{
bool left_is_type, left_is_explicit;
// If `left' is null, then we're called from SimpleNameResolve and this is
// a member in the currently defining class.
if (left == null) {
left_is_type = ec.IsStatic || ec.IsFieldInitializer;
left_is_explicit = false;
// Implicitly default to `this' unless we're static.
if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
left = ec.GetThis (loc);
} else {
left_is_type = left is TypeExpr;
left_is_explicit = true;
}
if (member_lookup is FieldExpr){
FieldExpr fe = (FieldExpr) member_lookup;
FieldInfo fi = fe.FieldInfo.Mono_GetGenericFieldDefinition ();
Type decl_type = fi.DeclaringType;
bool is_emitted = fi is FieldBuilder;
Type t = fi.FieldType;
if (is_emitted) {
Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
if (c != null) {
object o;
if (!c.LookupConstantValue (out o))
return null;
object real_value = ((Constant) c.Expr).GetValue ();
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) {
object o;
if (is_emitted)
o = TypeManager.GetValue ((FieldBuilder) fi);
else
o = fi.GetValue (fi);
if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
if (left_is_explicit && !left_is_type &&
!IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
error176 (loc, fe.FieldInfo.Name);
return null;
}
Expression enum_member = MemberLookup (
ec, decl_type, "value__", MemberTypes.Field,
AllBindingFlags, loc);
Enum en = TypeManager.LookupEnum (decl_type);
Constant c;
if (en != null)
c = Constantify (o, en.UnderlyingType);
else
c = Constantify (o, enum_member.Type);
return new EnumConstant (c, decl_type);
}
Expression exp = Constantify (o, t);
if (left_is_explicit && !left_is_type) {
error176 (loc, fe.FieldInfo.Name);
return null;
}
return exp;
}
if (t.IsPointer && !ec.InUnsafe){
UnsafeError (loc);
return null;
}
}
if (member_lookup is EventExpr) {
EventExpr ee = (EventExpr) member_lookup;
//
// If the event is local to this class, we transform ourselves into
// a FieldExpr
//
if (ee.EventInfo.DeclaringType == ec.ContainerType ||
TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
MemberInfo mi = GetFieldFromEvent (ee);
if (mi == null) {
//
// If this happens, then we have an event with its own
// accessors and private field etc so there's no need
// to transform ourselves.
//
ee.InstanceExpression = left;
return ee;
}
Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
if (ml == null) {
Report.Error (-200, loc, "Internal error!!");
return null;
}
if (!left_is_explicit)
left = null;
ee.InstanceExpression = left;
return ResolveMemberAccess (ec, ml, left, loc, left_original);
}
}
if (member_lookup is IMemberExpr) {
IMemberExpr me = (IMemberExpr) member_lookup;
MethodGroupExpr mg = me as MethodGroupExpr;
if (left_is_type){
if ((mg != null) && left_is_explicit && left.Type.IsInterface)
mg.IsExplicitImpl = left_is_explicit;
if (!me.IsStatic){
if ((ec.IsFieldInitializer || ec.IsStatic) &&
IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
return member_lookup;
SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
return null;
}
} else {
if (!me.IsInstance){
if (IdenticalNameAndTypeName (ec, left_original, left, loc))
return member_lookup;
if (left_is_explicit) {
error176 (loc, me.Name);
return null;
}
}
//
// Since we can not check for instance objects in SimpleName,
// becaue of the rule that allows types and variables to share
// the name (as long as they can be de-ambiguated later, see
// IdenticalNameAndTypeName), we have to check whether left
// is an instance variable in a static context
//
// However, if the left-hand value is explicitly given, then
// it is already our instance expression, so we aren't in
// static context.
//
if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
IMemberExpr mexp = (IMemberExpr) left;
if (!mexp.IsStatic){
SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
return null;
}
}
if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
mg.IdenticalTypeName = true;
me.InstanceExpression = left;
}
return member_lookup;
}
Console.WriteLine ("Left is: " + left);
Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
Environment.Exit (1);
return null;
}
public virtual Expression DoResolve (EmitContext ec, Expression right_side,
ResolveFlags flags)
{
if (type != null)
throw new Exception ();
//
// Resolve the expression with flow analysis turned off, we'll do the definite
// assignment checks later. This is because we don't know yet what the expression
// will resolve to - it may resolve to a FieldExpr and in this case we must do the
// definite assignment check on the actual field and not on the whole struct.
//
Expression original = expr;
expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
if (expr == null)
return null;
if (expr is Namespace) {
Namespace ns = (Namespace) expr;
string lookup_id = MemberName.MakeName (Identifier, args);
FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
if ((retval != null) && (args != null))
retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
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;
}
//
// TODO: I mailed Ravi about this, and apparently we can get rid
// of this and put it in the right place.
//
// Handle enums here when they are in transit.
// Note that we cannot afford to hit MemberLookup in this case because
// it will fail to find any members at all
//
Type expr_type;
if (expr is TypeExpr){
expr_type = expr.Type;
if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
return null;
}
if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
Enum en = TypeManager.LookupEnum (expr_type);
if (en != null) {
object value = en.LookupEnumValue (ec, Identifier, loc);
if (value != null){
MemberCore mc = en.GetDefinition (Identifier);
ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
if (oa != null) {
AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
}
oa = en.GetObsoleteAttribute (en);
if (oa != null) {
AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
}
Constant c = Constantify (value, en.UnderlyingType);
return new EnumConstant (c, expr_type);
}
} else {
CheckObsoleteAttribute (expr_type);
FieldInfo fi = expr_type.GetField (Identifier);
if (fi != null) {
ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
if (oa != null)
AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
}
}
}
} else
expr_type = expr.Type;
if (expr_type.IsPointer){
Error (23, "The `.' operator can not be applied to pointer operands (" +
TypeManager.CSharpName (expr_type) + ")");
return null;
}
Expression member_lookup;
member_lookup = MemberLookup (
ec, expr_type, expr_type, Identifier, loc);
if ((member_lookup == null) && (args != null)) {
string lookup_id = MemberName.MakeName (Identifier, args);
member_lookup = MemberLookup (
ec, expr_type, expr_type, lookup_id, loc);
}
if (member_lookup == null) {
MemberLookupFailed (
ec, expr_type, expr_type, Identifier, null, false, loc);
return null;
}
if (member_lookup is TypeExpr) {
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;
}
return member_lookup;
}
if (args != null) {
string full_name = expr_type + "." + Identifier;
if (member_lookup is FieldExpr) {
Report.Error (307, loc, "The field `{0}' cannot " +
"be used with type arguments", full_name);
return null;
} else if (member_lookup is EventExpr) {
Report.Error (307, loc, "The event `{0}' cannot " +
"be used with type arguments", full_name);
return null;
} else if (member_lookup is PropertyExpr) {
Report.Error (307, loc, "The property `{0}' cannot " +
"be used with type arguments", full_name);
return null;
}
}
member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
if (member_lookup == null)
return null;
if (args != null) {
MethodGroupExpr mg = member_lookup as MethodGroupExpr;
if (mg == null)
throw new InternalErrorException ();
return mg.ResolveGeneric (ec, args);
}
// The following DoResolve/DoResolveLValue will do the definite assignment
// check.
if (right_side != null)
member_lookup = member_lookup.DoResolveLValue (ec, right_side);
else
member_lookup = member_lookup.DoResolve (ec);
return member_lookup;
}
public override Expression DoResolve (EmitContext ec)
{
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.Type);
}
public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
{
return ResolveNamespaceOrType (ec, false);
}
public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
{
FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec);
if (new_expr == null)
return null;
string lookup_id = MemberName.MakeName (Identifier, args);
if (new_expr is Namespace) {
Namespace ns = (Namespace) new_expr;
FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
if ((retval != null) && (args != null))
retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
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;
}
TypeExpr tnew_expr = new_expr.ResolveAsTypeTerminal (ec);
if (tnew_expr == null)
return null;
Type expr_type = tnew_expr.Type;
if (expr_type.IsPointer){
Error (23, "The `.' operator can not be applied to pointer operands (" +
TypeManager.CSharpName (expr_type) + ")");
return null;
}
Expression member_lookup = MemberLookup (ec, expr_type, expr_type, lookup_id, loc);
if (member_lookup == null) {
int errors = Report.Errors;
MemberLookupFailed (ec, expr_type, expr_type, lookup_id, null, false, loc);
if (!silent && errors == Report.Errors)
Report.Error (234, loc, "The type name `{0}' could not be found in type `{1}'",
lookup_id, new_expr.FullName);
return null;
}
if (!(member_lookup is TypeExpr)) {
Report.Error (118, loc, "'{0}.{1}' denotes a '{2}', where a type was expected",
new_expr.FullName, lookup_id, member_lookup.ExprClassName ());
return null;
}
TypeExpr texpr = member_lookup.ResolveAsTypeTerminal (ec);
if (texpr == null)
return null;
TypeArguments the_args = args;
if (TypeManager.HasGenericArguments (expr_type)) {
Type[] decl_args = TypeManager.GetTypeArguments (expr_type);
TypeArguments new_args = new TypeArguments (loc);
foreach (Type decl in decl_args)
new_args.Add (new TypeExpression (decl, loc));
if (args != null)
new_args.Add (args);
the_args = new_args;
}
if (the_args != null) {
ConstructedType ctype = new ConstructedType (texpr.Type, the_args, loc);
return ctype.ResolveAsTypeStep (ec);
}
return texpr;
}
public override void Emit (EmitContext ec)
{
throw new Exception ("Should not happen");
}
public override string ToString ()
{
return expr + "." + MemberName.MakeName (Identifier, args);
}
}
///
/// Implements checked expressions
///
public class CheckedExpr : Expression {
public Expression Expr;
public CheckedExpr (Expression e, Location l)
{
Expr = e;
loc = l;
}
public override Expression DoResolve (EmitContext ec)
{
bool last_check = ec.CheckState;
bool last_const_check = ec.ConstantCheckState;
ec.CheckState = true;
ec.ConstantCheckState = true;
Expr = Expr.Resolve (ec);
ec.CheckState = last_check;
ec.ConstantCheckState = last_const_check;
if (Expr == null)
return null;
if (Expr is Constant)
return Expr;
eclass = Expr.eclass;
type = Expr.Type;
return this;
}
public override void Emit (EmitContext ec)
{
bool last_check = ec.CheckState;
bool last_const_check = ec.ConstantCheckState;
ec.CheckState = true;
ec.ConstantCheckState = true;
Expr.Emit (ec);
ec.CheckState = last_check;
ec.ConstantCheckState = last_const_check;
}
}
///
/// Implements the unchecked expression
///
public class UnCheckedExpr : Expression {
public Expression Expr;
public UnCheckedExpr (Expression e, Location l)
{
Expr = e;
loc = l;
}
public override Expression DoResolve (EmitContext ec)
{
bool last_check = ec.CheckState;
bool last_const_check = ec.ConstantCheckState;
ec.CheckState = false;
ec.ConstantCheckState = false;
Expr = Expr.Resolve (ec);
ec.CheckState = last_check;
ec.ConstantCheckState = last_const_check;
if (Expr == null)
return null;
if (Expr is Constant)
return Expr;
eclass = Expr.eclass;
type = Expr.Type;
return this;
}
public override void Emit (EmitContext ec)
{
bool last_check = ec.CheckState;
bool last_const_check = ec.ConstantCheckState;
ec.CheckState = false;
ec.ConstantCheckState = false;
Expr.Emit (ec);
ec.CheckState = last_check;
ec.ConstantCheckState = last_const_check;
}
}
///
/// An Element Access expression.
///
/// During semantic analysis these are transformed into
/// IndexerAccess, ArrayAccess or a PointerArithmetic.
///
public class ElementAccess : Expression {
public ArrayList Arguments;
public Expression Expr;
public ElementAccess (Expression e, ArrayList e_list, Location l)
{
Expr = e;
loc = l;
if (e_list == null)
return;
Arguments = new ArrayList ();
foreach (Expression tmp in e_list)
Arguments.Add (new Argument (tmp, Argument.AType.Expression));
}
bool CommonResolve (EmitContext ec)
{
Expr = Expr.Resolve (ec);
if (Expr == null)
return false;
if (Arguments == null)
return false;
foreach (Argument a in Arguments){
if (!a.Resolve (ec, loc))
return false;
}
return true;
}
Expression MakePointerAccess (EmitContext ec, Type t)
{
if (t == TypeManager.void_ptr_type){
Error (242, "The array index operation is not valid for void pointers");
return null;
}
if (Arguments.Count != 1){
Error (196, "A pointer must be indexed by a single value");
return null;
}
Expression p;
p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
if (p == null)
return null;
return new Indirection (p, loc).Resolve (ec);
}
public override Expression DoResolve (EmitContext ec)
{
if (!CommonResolve (ec))
return null;
//
// We perform some simple tests, and then to "split" the emit and store
// code we create an instance of a different class, and return that.
//
// I am experimenting with this pattern.
//
Type t = Expr.Type;
if (t == TypeManager.array_type){
Report.Error (21, loc, "Cannot use indexer on System.Array");
return null;
}
if (t.IsArray)
return (new ArrayAccess (this, loc)).Resolve (ec);
if (t.IsPointer)
return MakePointerAccess (ec, Expr.Type);
FieldExpr fe = Expr as FieldExpr;
if (fe != null) {
IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
if (ff != null) {
return MakePointerAccess (ec, ff.ElementType);
}
}
return (new IndexerAccess (this, loc)).Resolve (ec);
}
public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
if (!CommonResolve (ec))
return null;
Type t = Expr.Type;
if (t.IsArray)
return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
if (t.IsPointer)
return MakePointerAccess (ec, Expr.Type);
FieldExpr fe = Expr as FieldExpr;
if (fe != null) {
IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
if (ff != null) {
// TODO: not sure whether it is correct
// if (!ec.InFixedInitializer) {
// if (!ec.InFixedInitializer) {
// Error (1666, "You cannot use fixed sized buffers contained in unfixed expressions. Try using the fixed statement.");
// return null;
// }
return MakePointerAccess (ec, ff.ElementType);
}
}
return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
}
public override void Emit (EmitContext ec)
{
throw new Exception ("Should never be reached");
}
}
///
/// Implements array access
///
public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
//
// Points to our "data" repository
//
ElementAccess ea;
LocalTemporary temp;
bool prepared;
public ArrayAccess (ElementAccess ea_data, Location l)
{
ea = ea_data;
eclass = ExprClass.Variable;
loc = l;
}
public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
return DoResolve (ec);
}
public override Expression DoResolve (EmitContext ec)
{
#if false
ExprClass eclass = ea.Expr.eclass;
// As long as the type is valid
if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
eclass == ExprClass.Value)) {
ea.Expr.Error_UnexpectedKind ("variable or value");
return null;
}
#endif
Type t = ea.Expr.Type;
if (t.GetArrayRank () != ea.Arguments.Count){
ea.Error (22,
"Incorrect number of indexes for array " +
" expected: " + t.GetArrayRank () + " got: " +
ea.Arguments.Count);
return null;
}
type = TypeManager.GetElementType (t);
if (type.IsPointer && !ec.InUnsafe){
UnsafeError (ea.Location);
return null;
}
foreach (Argument a in ea.Arguments){
Type argtype = a.Type;
if (argtype == TypeManager.int32_type ||
argtype == TypeManager.uint32_type ||
argtype == TypeManager.int64_type ||
argtype == TypeManager.uint64_type) {
Constant c = a.Expr as Constant;
if (c != null && c.IsNegative) {
Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
}
continue;
}
//
// Mhm. This is strage, because the Argument.Type is not the same as
// Argument.Expr.Type: the value changes depending on the ref/out setting.
//
// Wonder if I will run into trouble for this.
//
a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
if (a.Expr == null)
return null;
}
eclass = ExprClass.Variable;
return this;
}
///
/// Emits the right opcode to load an object of Type `t'
/// from an array of T
///
static public void EmitLoadOpcode (ILGenerator ig, Type type)
{
if (type == TypeManager.byte_type || type == TypeManager.bool_type)
ig.Emit (OpCodes.Ldelem_U1);
else if (type == TypeManager.sbyte_type)
ig.Emit (OpCodes.Ldelem_I1);
else if (type == TypeManager.short_type)
ig.Emit (OpCodes.Ldelem_I2);
else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
ig.Emit (OpCodes.Ldelem_U2);
else if (type == TypeManager.int32_type)
ig.Emit (OpCodes.Ldelem_I4);
else if (type == TypeManager.uint32_type)
ig.Emit (OpCodes.Ldelem_U4);
else if (type == TypeManager.uint64_type)
ig.Emit (OpCodes.Ldelem_I8);
else if (type == TypeManager.int64_type)
ig.Emit (OpCodes.Ldelem_I8);
else if (type == TypeManager.float_type)
ig.Emit (OpCodes.Ldelem_R4);
else if (type == TypeManager.double_type)
ig.Emit (OpCodes.Ldelem_R8);
else if (type == TypeManager.intptr_type)
ig.Emit (OpCodes.Ldelem_I);
else if (TypeManager.IsEnumType (type)){
EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
} else if (type.IsValueType){
ig.Emit (OpCodes.Ldelema, type);
ig.Emit (OpCodes.Ldobj, type);
} else if (type.IsGenericParameter)
ig.Emit (OpCodes.Ldelem_Any, type);
else
ig.Emit (OpCodes.Ldelem_Ref);
}
///
/// Returns the right opcode to store an object of Type `t'
/// from an array of T.
///
static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
{
//Console.WriteLine (new System.Diagnostics.StackTrace ());
has_type_arg = false; is_stobj = false;
t = TypeManager.TypeToCoreType (t);
if (TypeManager.IsEnumType (t))
t = TypeManager.EnumToUnderlying (t);
if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
t == TypeManager.bool_type)
return OpCodes.Stelem_I1;
else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
t == TypeManager.char_type)
return OpCodes.Stelem_I2;
else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
return OpCodes.Stelem_I4;
else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
return OpCodes.Stelem_I8;
else if (t == TypeManager.float_type)
return OpCodes.Stelem_R4;
else if (t == TypeManager.double_type)
return OpCodes.Stelem_R8;
else if (t == TypeManager.intptr_type) {
has_type_arg = true;
is_stobj = true;
return OpCodes.Stobj;
} else if (t.IsValueType) {
has_type_arg = true;
is_stobj = true;
return OpCodes.Stobj;
} else if (t.IsGenericParameter) {
has_type_arg = true;
return OpCodes.Stelem_Any;
} else
return OpCodes.Stelem_Ref;
}
MethodInfo FetchGetMethod ()
{
ModuleBuilder mb = CodeGen.Module.Builder;
int arg_count = ea.Arguments.Count;
Type [] args = new Type [arg_count];
MethodInfo get;
for (int i = 0; i < arg_count; i++){
//args [i++] = a.Type;
args [i] = TypeManager.int32_type;
}
get = mb.GetArrayMethod (
ea.Expr.Type, "Get",
CallingConventions.HasThis |
CallingConventions.Standard,
type, args);
return get;
}
MethodInfo FetchAddressMethod ()
{
ModuleBuilder mb = CodeGen.Module.Builder;
int arg_count = ea.Arguments.Count;
Type [] args = new Type [arg_count];
MethodInfo address;
Type ret_type;
ret_type = TypeManager.GetReferenceType (type);
for (int i = 0; i < arg_count; i++){
//args [i++] = a.Type;
args [i] = TypeManager.int32_type;
}
address = mb.GetArrayMethod (
ea.Expr.Type, "Address",
CallingConventions.HasThis |
CallingConventions.Standard,
ret_type, args);
return address;
}
//
// Load the array arguments into the stack.
//
// If we have been requested to cache the values (cached_locations array
// initialized), then load the arguments the first time and store them
// in locals. otherwise load from local variables.
//
void LoadArrayAndArguments (EmitContext ec)
{
ILGenerator ig = ec.ig;
ea.Expr.Emit (ec);
foreach (Argument a in ea.Arguments){
Type argtype = a.Expr.Type;
a.Expr.Emit (ec);
if (argtype == TypeManager.int64_type)
ig.Emit (OpCodes.Conv_Ovf_I);
else if (argtype == TypeManager.uint64_type)
ig.Emit (OpCodes.Conv_Ovf_I_Un);
}
}
public void Emit (EmitContext ec, bool leave_copy)
{
int rank = ea.Expr.Type.GetArrayRank ();
ILGenerator ig = ec.ig;
if (!prepared) {
LoadArrayAndArguments (ec);
if (rank == 1)
EmitLoadOpcode (ig, type);
else {
MethodInfo method;
method = FetchGetMethod ();
ig.Emit (OpCodes.Call, method);
}
} else
LoadFromPtr (ec.ig, this.type);
if (leave_copy) {
ec.ig.Emit (OpCodes.Dup);
temp = new LocalTemporary (ec, this.type);
temp.Store (ec);
}
}
public override void Emit (EmitContext ec)
{
Emit (ec, false);
}
public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
{
int rank = ea.Expr.Type.GetArrayRank ();
ILGenerator ig = ec.ig;
Type t = source.Type;
prepared = prepare_for_load;
if (prepare_for_load) {
AddressOf (ec, AddressOp.LoadStore);
ec.ig.Emit (OpCodes.Dup);
source.Emit (ec);
if (leave_copy) {
ec.ig.Emit (OpCodes.Dup);
temp = new LocalTemporary (ec, this.type);
temp.Store (ec);
}
StoreFromPtr (ec.ig, t);
if (temp != null)
temp.Emit (ec);
return;
}
LoadArrayAndArguments (ec);
if (rank == 1) {
bool is_stobj, has_type_arg;
OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
//
// The stobj opcode used by value types will need
// an address on the stack, not really an array/array
// pair
//
if (is_stobj)
ig.Emit (OpCodes.Ldelema, t);
source.Emit (ec);
if (leave_copy) {
ec.ig.Emit (OpCodes.Dup);
temp = new LocalTemporary (ec, this.type);
temp.Store (ec);
}
if (is_stobj)
ig.Emit (OpCodes.Stobj, t);
else if (has_type_arg)
ig.Emit (op, t);
else
ig.Emit (op);
} else {
ModuleBuilder mb = CodeGen.Module.Builder;
int arg_count = ea.Arguments.Count;
Type [] args = new Type [arg_count + 1];
MethodInfo set;
source.Emit (ec);
if (leave_copy) {
ec.ig.Emit (OpCodes.Dup);
temp = new LocalTemporary (ec, this.type);
temp.Store (ec);
}
for (int i = 0; i < arg_count; i++){
//args [i++] = a.Type;
args [i] = TypeManager.int32_type;
}
args [arg_count] = type;
set = mb.GetArrayMethod (
ea.Expr.Type, "Set",
CallingConventions.HasThis |
CallingConventions.Standard,
TypeManager.void_type, args);
ig.Emit (OpCodes.Call, set);
}
if (temp != null)
temp.Emit (ec);
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
int rank = ea.Expr.Type.GetArrayRank ();
ILGenerator ig = ec.ig;
LoadArrayAndArguments (ec);
if (rank == 1){
ig.Emit (OpCodes.Ldelema, type);
} else {
MethodInfo address = FetchAddressMethod ();
ig.Emit (OpCodes.Call, address);
}
}
}
class Indexers {
public ArrayList Properties;
static Hashtable map;
public struct Indexer {
public readonly Type Type;
public readonly MethodInfo Getter, Setter;
public Indexer (Type type, MethodInfo get, MethodInfo set)
{
this.Type = type;
this.Getter = get;
this.Setter = set;
}
}
static Indexers ()
{
map = new Hashtable ();
}
Indexers ()
{
Properties = new ArrayList ();
}
void Append (MemberInfo [] mi)
{
foreach (PropertyInfo property in mi){
MethodInfo get, set;
get = property.GetGetMethod (true);
set = property.GetSetMethod (true);
Properties.Add (new Indexer (property.PropertyType, get, set));
}
}
static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
{
string p_name = TypeManager.IndexerPropertyName (lookup_type);
MemberInfo [] mi = TypeManager.MemberLookup (
caller_type, caller_type, lookup_type, MemberTypes.Property,
BindingFlags.Public | BindingFlags.Instance |
BindingFlags.DeclaredOnly, p_name, null);
if (mi == null || mi.Length == 0)
return null;
return mi;
}
static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
{
Indexers ix = (Indexers) map [lookup_type];
if (ix != null)
return ix;
Type copy = lookup_type;
while (copy != TypeManager.object_type && copy != null){
MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
if (mi != null){
if (ix == null)
ix = new Indexers ();
ix.Append (mi);
}
copy = copy.BaseType;
}
if (!lookup_type.IsInterface)
return ix;
Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
if (ifaces != null) {
foreach (Type itype in ifaces) {
MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
if (mi != null){
if (ix == null)
ix = new Indexers ();
ix.Append (mi);
}
}
}
return ix;
}
}
///
/// Expressions that represent an indexer call.
///
public class IndexerAccess : Expression, IAssignMethod {
//
// Points to our "data" repository
//
MethodInfo get, set;
ArrayList set_arguments;
bool is_base_indexer;
protected Type indexer_type;
protected Type current_type;
protected Expression instance_expr;
protected ArrayList arguments;
public IndexerAccess (ElementAccess ea, Location loc)
: this (ea.Expr, false, loc)
{
this.arguments = ea.Arguments;
}
protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
Location loc)
{
this.instance_expr = instance_expr;
this.is_base_indexer = is_base_indexer;
this.eclass = ExprClass.Value;
this.loc = loc;
}
protected virtual bool CommonResolve (EmitContext ec)
{
indexer_type = instance_expr.Type;
current_type = ec.ContainerType;
return true;
}
public override Expression DoResolve (EmitContext ec)
{
ArrayList AllGetters = new ArrayList();
if (!CommonResolve (ec))
return null;
//
// Step 1: Query for all `Item' *properties*. Notice
// that the actual methods are pointed from here.
//
// This is a group of properties, piles of them.
bool found_any = false, found_any_getters = false;
Type lookup_type = indexer_type;
Indexers ilist;
ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
if (ilist != null) {
found_any = true;
if (ilist.Properties != null) {
foreach (Indexers.Indexer ix in ilist.Properties) {
if (ix.Getter != null)
AllGetters.Add(ix.Getter);
}
}
}
if (AllGetters.Count > 0) {
found_any_getters = true;
get = (MethodInfo) Invocation.OverloadResolve (
ec, new MethodGroupExpr (AllGetters, loc),
arguments, false, loc);
}
if (!found_any) {
Report.Error (21, loc,
"Type `" + TypeManager.CSharpName (indexer_type) +
"' does not have any indexers defined");
return null;
}
if (!found_any_getters) {
Error (154, "indexer can not be used in this context, because " +
"it lacks a `get' accessor");
return null;
}
if (get == null) {
Error (1501, "No Overload for method `this' takes `" +
arguments.Count + "' arguments");
return null;
}
//
// Only base will allow this invocation to happen.
//
if (get.IsAbstract && this is BaseIndexerAccess){
Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
return null;
}
type = get.ReturnType;
if (type.IsPointer && !ec.InUnsafe){
UnsafeError (loc);
return null;
}
instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
eclass = ExprClass.IndexerAccess;
return this;
}
public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
ArrayList AllSetters = new ArrayList();
if (!CommonResolve (ec))
return null;
bool found_any = false, found_any_setters = false;
Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
if (ilist != null) {
found_any = true;
if (ilist.Properties != null) {
foreach (Indexers.Indexer ix in ilist.Properties) {
if (ix.Setter != null)
AllSetters.Add(ix.Setter);
}
}
}
if (AllSetters.Count > 0) {
found_any_setters = true;
set_arguments = (ArrayList) arguments.Clone ();
set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
set = (MethodInfo) Invocation.OverloadResolve (
ec, new MethodGroupExpr (AllSetters, loc),
set_arguments, false, loc);
}
if (!found_any) {
Report.Error (21, loc,
"Type `" + TypeManager.CSharpName (indexer_type) +
"' does not have any indexers defined");
return null;
}
if (!found_any_setters) {
Error (154, "indexer can not be used in this context, because " +
"it lacks a `set' accessor");
return null;
}
if (set == null) {
Error (1501, "No Overload for method `this' takes `" +
arguments.Count + "' arguments");
return null;
}
//
// Only base will allow this invocation to happen.
//
if (set.IsAbstract && this is BaseIndexerAccess){
Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
return null;
}
//
// Now look for the actual match in the list of indexers to set our "return" type
//
type = TypeManager.void_type; // default value
foreach (Indexers.Indexer ix in ilist.Properties){
if (ix.Setter == set){
type = ix.Type;
break;
}
}
instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
eclass = ExprClass.IndexerAccess;
return this;
}
bool prepared = false;
LocalTemporary temp;
public void Emit (EmitContext ec, bool leave_copy)
{
Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
if (leave_copy) {
ec.ig.Emit (OpCodes.Dup);
temp = new LocalTemporary (ec, Type);
temp.Store (ec);
}
}
//
// source is ignored, because we already have a copy of it from the
// LValue resolution and we have already constructed a pre-cached
// version of the arguments (ea.set_arguments);
//
public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
{
prepared = prepare_for_load;
Argument a = (Argument) set_arguments [set_arguments.Count - 1];
if (prepared) {
source.Emit (ec);
if (leave_copy) {
ec.ig.Emit (OpCodes.Dup);
temp = new LocalTemporary (ec, Type);
temp.Store (ec);
}
} else if (leave_copy) {
temp = new LocalTemporary (ec, Type);
source.Emit (ec);
temp.Store (ec);
a.Expr = temp;
}
Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
if (temp != null)
temp.Emit (ec);
}
public override void Emit (EmitContext ec)
{
Emit (ec, false);
}
}
///
/// The base operator for method names
///
public class BaseAccess : Expression {
string member;
public BaseAccess (string member, Location l)
{
this.member = member;
loc = l;
}
public override Expression DoResolve (EmitContext ec)
{
Expression c = CommonResolve (ec);
if (c == null)
return null;
//
// MethodGroups use this opportunity to flag an error on lacking ()
//
if (!(c is MethodGroupExpr))
return c.Resolve (ec);
return c;
}
public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
Expression c = CommonResolve (ec);
if (c == null)
return null;
//
// MethodGroups use this opportunity to flag an error on lacking ()
//
if (! (c is MethodGroupExpr))
return c.DoResolveLValue (ec, right_side);
return c;
}
Expression CommonResolve (EmitContext ec)
{
Expression member_lookup;
Type current_type = ec.ContainerType;
Type base_type = current_type.BaseType;
Expression e;
if (ec.IsStatic){
Error (1511, "Keyword base is not allowed in static method");
return null;
}
if (ec.IsFieldInitializer){
Error (1512, "Keyword base is not available in the current context");
return null;
}
member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type,
member, AllMemberTypes, AllBindingFlags,
loc);
if (member_lookup == null) {
MemberLookupFailed (ec, base_type, base_type, member, null, true, loc);
return null;
}
Expression left;
if (ec.IsStatic)
left = new TypeExpression (base_type, loc);
else
left = ec.GetThis (loc);
e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
if (e is PropertyExpr){
PropertyExpr pe = (PropertyExpr) e;
pe.IsBase = true;
}
if (e is MethodGroupExpr)
((MethodGroupExpr) e).IsBase = true;
return e;
}
public override void Emit (EmitContext ec)
{
throw new Exception ("Should never be called");
}
}
///
/// The base indexer operator
///
public class BaseIndexerAccess : IndexerAccess {
public BaseIndexerAccess (ArrayList args, Location loc)
: base (null, true, loc)
{
arguments = new ArrayList ();
foreach (Expression tmp in args)
arguments.Add (new Argument (tmp, Argument.AType.Expression));
}
protected override bool CommonResolve (EmitContext ec)
{
instance_expr = ec.GetThis (loc);
current_type = ec.ContainerType.BaseType;
indexer_type = current_type;
foreach (Argument a in arguments){
if (!a.Resolve (ec, loc))
return false;
}
return true;
}
}
///
/// This class exists solely to pass the Type around and to be a dummy
/// that can be passed to the conversion functions (this is used by
/// foreach implementation to typecast the object return value from
/// get_Current into the proper type. All code has been generated and
/// we only care about the side effect conversions to be performed
///
/// This is also now used as a placeholder where a no-action expression
/// is needed (the `New' class).
///
public class EmptyExpression : Expression {
public static readonly EmptyExpression Null = new EmptyExpression ();
// TODO: should be protected
public EmptyExpression ()
{
type = TypeManager.object_type;
eclass = ExprClass.Value;
loc = Location.Null;
}
public EmptyExpression (Type t)
{
type = t;
eclass = ExprClass.Value;
loc = Location.Null;
}
public override Expression DoResolve (EmitContext ec)
{
return this;
}
public override void Emit (EmitContext ec)
{
// nothing, as we only exist to not do anything.
}
//
// This is just because we might want to reuse this bad boy
// instead of creating gazillions of EmptyExpressions.
// (CanImplicitConversion uses it)
//
public void SetType (Type t)
{
type = t;
}
}
public class UserCast : Expression {
MethodBase method;
Expression source;
public UserCast (MethodInfo method, Expression source, Location l)
{
this.method = method;
this.source = source;
type = method.ReturnType;
eclass = ExprClass.Value;
loc = l;
}
public Expression Source {
get {
return source;
}
}
public override Expression DoResolve (EmitContext ec)
{
//
// We are born fully resolved
//
return this;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
source.Emit (ec);
if (method is MethodInfo)
ig.Emit (OpCodes.Call, (MethodInfo) method);
else
ig.Emit (OpCodes.Call, (ConstructorInfo) method);
}
}
//
// This class is used to "construct" the type during a typecast
// operation. Since the Type.GetType class in .NET can parse
// the type specification, we just use this to construct the type
// one bit at a time.
//
public class ComposedCast : TypeExpr {
Expression left;
string dim;
public ComposedCast (Expression left, string dim, Location l)
{
this.left = left;
this.dim = dim;
loc = l;
}
protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
{
TypeExpr lexpr = left.ResolveAsTypeTerminal (ec);
if (lexpr == null)
return null;
Type ltype = lexpr.Type;
if ((ltype == TypeManager.void_type) && (dim != "*")) {
Report.Error (1547, Location,
"Keyword 'void' cannot be used in this context");
return null;
}
if ((dim.Length > 0) && (dim [0] == '?')) {
TypeExpr nullable = new NullableType (left, loc);
if (dim.Length > 1)
nullable = new ComposedCast (nullable, dim.Substring (1), loc);
return nullable.ResolveAsTypeTerminal (ec);
}
int pos = 0;
while ((pos < dim.Length) && (dim [pos] == '[')) {
pos++;
if (dim [pos] == ']') {
ltype = ltype.MakeArrayType ();
pos++;
if (pos < dim.Length)
continue;
type = ltype;
eclass = ExprClass.Type;
return this;
}
int rank = 0;
while (dim [pos] == ',') {
pos++; rank++;
}
if ((dim [pos] != ']') || (pos != dim.Length-1))
return null;
type = ltype.MakeArrayType (rank + 1);
eclass = ExprClass.Type;
return this;
}
if (dim != "") {
//
// ltype.Fullname is already fully qualified, so we can skip
// a lot of probes, and go directly to TypeManager.LookupType
//
string fname = ltype.FullName != null ? ltype.FullName : ltype.Name;
string cname = fname + dim;
type = TypeManager.LookupTypeDirect (cname);
if (type == null){
//
// For arrays of enumerations we are having a problem
// with the direct lookup. Need to investigate.
//
// For now, fall back to the full lookup in that case.
//
FullNamedExpression e = ec.DeclSpace.LookupType (
cname, loc, /*ignore_cs0104=*/ false);
if (e == null) {
Report.Error (246, loc, "Cannot find type `" + cname + "'");
return null;
}
if (e is TypeExpr)
type = ((TypeExpr) e).ResolveType (ec);
if (type == null)
return null;
}
} else {
type = ltype;
}
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;
return this;
}
public override string Name {
get {
return left + dim;
}
}
public override string FullName {
get {
return type.FullName;
}
}
}
public class FixedBufferPtr: Expression {
Expression array;
public FixedBufferPtr (Expression array, Type array_type, Location l)
{
this.array = array;
this.loc = l;
type = TypeManager.GetPointerType (array_type);
eclass = ExprClass.Value;
}
public override void Emit(EmitContext ec)
{
array.Emit (ec);
}
public override Expression DoResolve (EmitContext ec)
{
//
// We are born fully resolved
//
return this;
}
}
//
// This class is used to represent the address of an array, used
// only by the Fixed statement, this generates "&a [0]" construct
// for fixed (char *pa = a)
//
public class ArrayPtr : FixedBufferPtr {
Type array_type;
public ArrayPtr (Expression array, Type array_type, Location l):
base (array, array_type, l)
{
this.array_type = array_type;
}
public override void Emit (EmitContext ec)
{
base.Emit (ec);
ILGenerator ig = ec.ig;
IntLiteral.EmitInt (ig, 0);
ig.Emit (OpCodes.Ldelema, array_type);
}
}
//
// Used by the fixed statement
//
public class StringPtr : Expression {
LocalBuilder b;
public StringPtr (LocalBuilder b, Location l)
{
this.b = b;
eclass = ExprClass.Value;
type = TypeManager.char_ptr_type;
loc = l;
}
public override Expression DoResolve (EmitContext ec)
{
// This should never be invoked, we are born in fully
// initialized state.
return this;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
ig.Emit (OpCodes.Ldloc, b);
ig.Emit (OpCodes.Conv_I);
ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
ig.Emit (OpCodes.Add);
}
}
//
// Implements the `stackalloc' keyword
//
public class StackAlloc : Expression {
Type otype;
Expression t;
Expression count;
public StackAlloc (Expression type, Expression count, Location l)
{
t = type;
this.count = count;
loc = l;
}
public override Expression DoResolve (EmitContext ec)
{
count = count.Resolve (ec);
if (count == null)
return null;
if (count.Type != TypeManager.int32_type){
count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
if (count == null)
return null;
}
Constant c = count as Constant;
if (c != null && c.IsNegative) {
Report.Error (247, loc, "Cannot use a negative size with stackalloc");
return null;
}
if (ec.CurrentBranching.InCatch () ||
ec.CurrentBranching.InFinally (true)) {
Error (255,
"stackalloc can not be used in a catch or finally block");
return null;
}
TypeExpr texpr = t.ResolveAsTypeTerminal (ec);
if (texpr == null)
return null;
otype = texpr.Type;
if (!TypeManager.VerifyUnManaged (otype, loc))
return null;
type = TypeManager.GetPointerType (otype);
eclass = ExprClass.Value;
return this;
}
public override void Emit (EmitContext ec)
{
int size = GetTypeSize (otype);
ILGenerator ig = ec.ig;
if (size == 0)
ig.Emit (OpCodes.Sizeof, otype);
else
IntConstant.EmitInt (ig, size);
count.Emit (ec);
ig.Emit (OpCodes.Mul);
ig.Emit (OpCodes.Localloc);
}
}
}