Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
tree: 1407fccda3
Fetching contributors…

Cannot retrieve contributors at this time

executable file 7515 lines (6310 sloc) 194.094 kb
//
// expression.cs: Expression representation for the IL tree.
//
// Author:
// Miguel de Icaza (miguel@ximian.com)
//
// (C) 2001 Ximian, Inc.
//
//
#define USE_OLD
namespace Mono.CSharp {
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
/// <summary>
/// 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.
/// </summary>
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);
ec.ig.Emit (OpCodes.Call, mi);
return;
}
static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
Expression e, Location loc)
{
ArrayList args;
MethodBase method;
args = new ArrayList (1);
args.Add (new Argument (e, Argument.AType.Expression));
method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, 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);
}
}
/// <summary>
/// Unary expressions.
/// </summary>
///
/// <remarks>
/// Unary implements unary expressions. It derives from
/// ExpressionStatement becuase the pre/post increment/decrement
/// operators can be used in a statement context.
/// </remarks>
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;
}
/// <summary>
/// Returns a stringified representation of the Operator
/// </summary>
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) + "'");
}
/// <remarks>
/// The result has been already resolved:
///
/// FIXME: a minus constant -128 sbyte cant be turned into a
/// constant byte.
/// </remarks>
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);
return e;
}
// <summary>
// 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
// </summary>
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 true;
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 (ImplicitConversionExists (ec, e, TypeManager.int32_type)){
result = new Cast (new TypeExpr (TypeManager.int32_type, loc), e, loc);
result = result.Resolve (ec);
} else if (ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
result = new Cast (new TypeExpr (TypeManager.uint32_type, loc), e, loc);
result = result.Resolve (ec);
} else if (ImplicitConversionExists (ec, e, TypeManager.int64_type)){
result = new Cast (new TypeExpr (TypeManager.int64_type, loc), e, loc);
result = result.Resolve (ec);
} else if (ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
result = new Cast (new TypeExpr (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)
{
Type expr_type = Expr.Type;
//
// Step 1: Perform Operator Overload location
//
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;
//
// Step 2: Default operations on CLI native types.
//
// Attempt to use a constant folding operation.
if (Expr is Constant){
Expression result;
if (Reduce (ec, (Constant) Expr, out result))
return result;
}
switch (Oper){
case Operator.LogicalNot:
if (expr_type != TypeManager.bool_type) {
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 = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
if (e != null){
type = TypeManager.int32_type;
return this;
}
e = ConvertImplicit (ec, Expr, TypeManager.uint32_type, loc);
if (e != null){
type = TypeManager.uint32_type;
return this;
}
e = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
if (e != null){
type = TypeManager.int64_type;
return this;
}
e = ConvertImplicit (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 (Expr.eclass != ExprClass.Variable){
Error (211, "Cannot take the address of non-variables");
return null;
}
if (!ec.InUnsafe) {
UnsafeError (loc);
return null;
}
if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
return null;
}
string ptr_type_name = Expr.Type.FullName + "*";
type = TypeManager.LookupType (ptr_type_name);
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
// ConvertImplicit 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 = ConvertImplicit (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 = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
if (expr != null){
Expr = expr;
type = expr.Type;
return this;
}
expr = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
if (expr != null){
Expr = expr;
type = expr.Type;
return this;
}
expr = ConvertImplicit (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.ResolveLValue (ec, new EmptyExpression ());
else
Expr = Expr.Resolve (ec);
if (Expr == null)
return null;
eclass = ExprClass.Value;
return ResolveOperator (ec);
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
Type expr_type = Expr.Type;
switch (Oper) {
case Operator.UnaryPlus:
throw new Exception ("This should be caught by Resolve");
case Operator.UnaryNegation:
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 ());
}
}
/// <summary>
/// This will emit the child expression for `ec' avoiding the logical
/// not. The parent will take care of changing brfalse/brtrue
/// </summary>
public void EmitLogicalNot (EmitContext ec)
{
if (Oper != Operator.LogicalNot)
throw new Exception ("EmitLogicalNot can only be called with !expr");
Expr.Emit (ec);
}
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 {
Expression expr;
LocalTemporary temporary;
bool have_temporary;
public Indirection (Expression expr, Location l)
{
this.expr = expr;
this.type = TypeManager.TypeToCoreType (expr.Type.GetElementType ());
eclass = ExprClass.Variable;
loc = l;
}
void LoadExprValue (EmitContext ec)
{
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
if (temporary != null){
if (have_temporary){
temporary.Emit (ec);
return;
}
expr.Emit (ec);
ec.ig.Emit (OpCodes.Dup);
temporary.Store (ec);
have_temporary = true;
} else
expr.Emit (ec);
LoadFromPtr (ig, Type);
}
public void EmitAssign (EmitContext ec, Expression source)
{
if (temporary != null){
if (have_temporary)
temporary.Emit (ec);
else {
expr.Emit (ec);
ec.ig.Emit (OpCodes.Dup);
temporary.Store (ec);
have_temporary = true;
}
} else
expr.Emit (ec);
source.Emit (ec);
StoreFromPtr (ec.ig, type);
}
public void AddressOf (EmitContext ec, AddressOp Mode)
{
if (temporary != null){
if (have_temporary){
temporary.Emit (ec);
return;
}
expr.Emit (ec);
ec.ig.Emit (OpCodes.Dup);
temporary.Store (ec);
have_temporary = true;
} else
expr.Emit (ec);
}
public override Expression DoResolve (EmitContext ec)
{
//
// Born fully resolved
//
return this;
}
public new void CacheTemporaries (EmitContext ec)
{
temporary = new LocalTemporary (ec, type);
}
}
/// <summary>
/// Unary Mutator expressions (pre and post ++ and --)
/// </summary>
///
/// <remarks>
/// 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)
///
/// </remarks>
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;
Expression expr;
LocalTemporary temp_storage;
//
// This is expensive for the simplest case.
//
Expression 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) + "'");
}
/// <summary>
/// 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)
/// </summary>
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 && expr_type.BaseType != null)
mg = MemberLookup (ec, expr_type.BaseType, op_name,
MemberTypes.Method, AllBindingFlags, loc);
if (mg != null) {
method = StaticCallExpr.MakeSimpleCall (
ec, (MethodGroupExpr) mg, expr, loc);
type = method.Type;
return this;
}
//
// 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){
if (IsIncrementableNumber (expr_type) ||
expr_type == TypeManager.decimal_type){
return this;
}
} else if (expr.eclass == ExprClass.IndexerAccess){
IndexerAccess ia = (IndexerAccess) expr;
temp_storage = new LocalTemporary (ec, expr.Type);
expr = ia.ResolveLValue (ec, temp_storage);
if (expr == null)
return null;
return this;
} else if (expr.eclass == ExprClass.PropertyAccess){
PropertyExpr pe = (PropertyExpr) expr;
if (pe.VerifyAssignable ())
return this;
return null;
} else {
expr.Error118 ("variable, indexer or property access");
return null;
}
Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
TypeManager.CSharpName (expr_type) + "'");
return null;
}
public override Expression DoResolve (EmitContext ec)
{
expr = expr.Resolve (ec);
if (expr == null)
return null;
eclass = ExprClass.Value;
return ResolveOperator (ec);
}
static int PtrTypeSize (Type t)
{
return GetTypeSize (t.GetElementType ());
}
//
// 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)
{
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);
}
}
void EmitCode (EmitContext ec, bool is_expr)
{
ILGenerator ig = ec.ig;
IAssignMethod ia = (IAssignMethod) expr;
Type expr_type = expr.Type;
ia.CacheTemporaries (ec);
if (temp_storage == null)
temp_storage = new LocalTemporary (ec, expr_type);
switch (mode){
case Mode.PreIncrement:
case Mode.PreDecrement:
if (method == null){
expr.Emit (ec);
LoadOneAndEmitOp (ec, expr_type);
} else
method.Emit (ec);
temp_storage.Store (ec);
ia.EmitAssign (ec, temp_storage);
if (is_expr)
temp_storage.Emit (ec);
break;
case Mode.PostIncrement:
case Mode.PostDecrement:
if (is_expr)
expr.Emit (ec);
if (method == null){
if (!is_expr)
expr.Emit (ec);
else
ig.Emit (OpCodes.Dup);
LoadOneAndEmitOp (ec, expr_type);
} else {
method.Emit (ec);
}
temp_storage.Store (ec);
ia.EmitAssign (ec, temp_storage);
break;
}
}
public override void Emit (EmitContext ec)
{
EmitCode (ec, true);
}
public override void EmitStatement (EmitContext ec)
{
EmitCode (ec, false);
}
}
/// <summary>
/// Base class for the `Is' and `As' classes.
/// </summary>
///
/// <remarks>
/// FIXME: Split this in two, and we get to save the `Operator' Oper
/// size.
/// </remarks>
public abstract class Probe : Expression {
public readonly 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)
{
probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
if (probe_type == null)
return null;
expr = expr.Resolve (ec);
return this;
}
}
/// <summary>
/// Implementation of the `is' operator.
/// </summary>
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 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 = ConvertImplicitStandard (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 (ExplicitReferenceConversionExists (etype, probe_type)){
//
// 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 (RootContext.WarningLevel >= 1){
if (warning_always_matches)
Warning (
183,
"The expression is always of type `" +
TypeManager.CSharpName (probe_type) + "'");
else if (warning_never_matches){
if (!(probe_type.IsInterface || expr.Type.IsInterface))
Warning (
184,
"The expression is never of type `" +
TypeManager.CSharpName (probe_type) + "'");
}
}
return this;
}
}
/// <summary>
/// Implementation of the `as' operator.
/// </summary>
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 = ConvertImplicit (ec, expr, probe_type, loc);
if (e != null){
expr = e;
do_isinst = false;
return this;
}
if (ExplicitReferenceConversionExists (etype, probe_type)){
do_isinst = true;
return this;
}
Error_CannotConvertType (etype, probe_type, loc);
return null;
}
}
/// <summary>
/// This represents a typecast in the source language.
///
/// FIXME: Cast expressions have an unusual set of parsing
/// rules, we need to figure those out.
/// </summary>
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;
}
/// <summary>
/// Attempts to do a compile-time folding of a constant cast.
/// </summary>
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 DoResolve (EmitContext ec)
{
expr = expr.Resolve (ec);
if (expr == null)
return null;
int errors = Report.Errors;
type = ec.DeclSpace.ResolveType (target_type, false, Location);
if (type == null)
return null;
eclass = ExprClass.Value;
if (expr is Constant){
Expression e = TryReduce (ec, type);
if (e != null)
return e;
}
expr = ConvertExplicit (ec, expr, type, loc);
return expr;
}
public override void Emit (EmitContext ec)
{
//
// This one will never happen
//
throw new Exception ("Should not happen");
}
}
/// <summary>
/// Binary operators
/// </summary>
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;
//
// After resolution, method might contain the operator overload
// method.
//
protected MethodBase method;
ArrayList Arguments;
bool DelegateOperation;
// 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;
}
}
/// <summary>
/// Returns a stringified representation of the Operator
/// </summary>
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 ConvertImplicit (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 (ImplicitUserConversionExists (ec, l, t))
return true;
else if (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 = ConvertImplicit (ec, right, TypeManager.double_type, loc);
if (l != TypeManager.double_type)
left = ConvertImplicit (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 = ConvertImplicit (ec, right, TypeManager.float_type, loc);
if (l != TypeManager.double_type)
left = ConvertImplicit (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 = 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 = ImplicitNumericConversion (ec, right, l, loc);
if (e != null)
right = e;
}
}
other = right.Type;
} else {
if (left is IntConstant){
e = 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 = 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);
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 = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
if (r != TypeManager.int64_type)
right = ConvertImplicit (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.
//
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 = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
if (r != TypeManager.decimal_type)
right = ConvertImplicit (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_32_or_64 (Type t)
{
return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
t == TypeManager.int64_type || t == TypeManager.uint64_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 CheckShiftArguments (EmitContext ec)
{
Expression e;
Type l = left.Type;
Type r = right.Type;
e = ForceConversion (ec, right, TypeManager.int32_type);
if (e == null){
Error_OperatorCannotBeApplied ();
return null;
}
right = e;
if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
left = e;
type = e.Type;
return this;
}
Error_OperatorCannotBeApplied ();
return null;
}
Expression ResolveOperator (EmitContext ec)
{
Type l = left.Type;
Type r = right.Type;
bool overload_failed = false;
//
// Special cases: string comapred to null
//
if (oper == Operator.Equality || oper == Operator.Inequality){
if ((l == TypeManager.string_type && (right is NullLiteral)) ||
(r == TypeManager.string_type && (left is NullLiteral))){
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) {
Arguments = new ArrayList ();
Arguments.Add (new Argument (left, Argument.AType.Expression));
Arguments.Add (new Argument (right, Argument.AType.Expression));
method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
if (method != null) {
MethodInfo mi = (MethodInfo) method;
type = mi.ReturnType;
return this;
} else {
overload_failed = true;
}
}
}
//
// Step 2: Default operations on CLI native types.
//
//
// 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
//
if (l == TypeManager.string_type){
if (r == TypeManager.void_type) {
Error_OperatorCannotBeApplied ();
return null;
}
if (r == TypeManager.string_type){
if (left is Constant && right is Constant){
StringConstant ls = (StringConstant) left;
StringConstant rs = (StringConstant) right;
return new StringConstant (
ls.Value + rs.Value);
}
if (left is Binary){
Binary b = (Binary) left;
//
// Call String.Concat (string, string, string) or
// String.Concat (string, string, string, string)
// if possible.
//
if (b.oper == Operator.Addition &&
(b.method == TypeManager.string_concat_string_string_string ||
b.method == TypeManager.string_concat_string_string_string_string)){
ArrayList bargs = b.Arguments;
int count = bargs.Count;
if (count == 2){
Arguments = bargs;
Arguments.Add (new Argument (right, Argument.AType.Expression));
type = TypeManager.string_type;
method = TypeManager.string_concat_string_string_string;
return this;
} else if (count == 3){
Arguments = bargs;
Arguments.Add (new Argument (right, Argument.AType.Expression));
type = TypeManager.string_type;
method = TypeManager.string_concat_string_string_string_string;
return this;
}
}
}
// string + string
method = TypeManager.string_concat_string_string;
} else {
// string + object
method = TypeManager.string_concat_object_object;
right = ConvertImplicit (ec, right,
TypeManager.object_type, loc);
if (right == null){
Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
return null;
}
}
type = TypeManager.string_type;
Arguments = new ArrayList ();
Arguments.Add (new Argument (left, Argument.AType.Expression));
Arguments.Add (new Argument (right, Argument.AType.Expression));
return this;
} else if (r == TypeManager.string_type){
// object + string
if (l == TypeManager.void_type) {
Error_OperatorCannotBeApplied ();
return null;
}
method = TypeManager.string_concat_object_object;
left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
if (left == null){
Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
return null;
}
Arguments = new ArrayList ();
Arguments.Add (new Argument (left, Argument.AType.Expression));
Arguments.Add (new Argument (right, Argument.AType.Expression));
type = TypeManager.string_type;
return this;
}
//
// 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;
}
//
// 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 (!(StandardConversionExists (left, r) ||
StandardConversionExists (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 (l.IsSubclassOf (TypeManager.delegate_type) &&
r.IsSubclassOf (TypeManager.delegate_type)) {
Arguments = new ArrayList ();
Arguments.Add (new Argument (left, Argument.AType.Expression));
Arguments.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 (l != r) {
Error_OperatorCannotBeApplied ();
return null;
}
DelegateOperation = true;
type = l;
return this;
}
//
// 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);
} else if (is_32_or_64 (r))
return new PointerArithmetic (
oper == Operator.Addition, left, right, l, loc);
} else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
return new PointerArithmetic (
true, right, left, r, loc);
}
//
// 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 && 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){
Error_OperatorCannotBeApplied ();
return null;
}
type = enum_type;
return this;
}
if (!rie){
temp = ConvertImplicit (ec, right, l, loc);
if (temp != null)
right = temp;
else {
Error_OperatorCannotBeApplied ();
return null;
}
} if (!lie){
temp = ConvertImplicit (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){
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){
Error_OperatorCannotBeApplied ();
return null;
}
type = TypeManager.bool_type;
return this;
}
//
// 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;
}
}
//
// We are dealing with numbers
//
if (overload_failed){
Error_OperatorCannotBeApplied ();
return null;
}
//
// 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.int64_type) ||
(l == TypeManager.uint64_type)))
type = l;
} 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)
{
left = left.Resolve (ec);
right = right.Resolve (ec);
if (left == null || right == null)
return null;
eclass = ExprClass.Value;
Constant rc = right as Constant;
Constant lc = left as Constant;
if (rc != null & lc != null){
Expression e = ConstantFold.BinaryFold (
ec, oper, lc, rc, loc);
if (e != null)
return e;
}
return ResolveOperator (ec);
}
/// <remarks>
/// 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
/// </remarks>
public bool EmitBranchable (EmitContext ec, Label target, bool onTrue)
{
if (method != null)
return false;
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){
bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
if (left is NullLiteral){
right.Emit (ec);
if (my_on_true)
ig.Emit (OpCodes.Brtrue, target);
else
ig.Emit (OpCodes.Brfalse, target);
return true;
} else if (right is NullLiteral){
left.Emit (ec);
if (my_on_true)
ig.Emit (OpCodes.Brtrue, target);
else
ig.Emit (OpCodes.Brfalse, target);
return true;
} else if (left is BoolConstant){
right.Emit (ec);
if (my_on_true != ((BoolConstant) left).Value)
ig.Emit (OpCodes.Brtrue, target);
else
ig.Emit (OpCodes.Brfalse, target);
return true;
} 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 true;
}
} else if (oper == Operator.LogicalAnd){
if (left is Binary){
Binary left_binary = (Binary) left;
if (onTrue){
Label tests_end = ig.DefineLabel ();
if (left_binary.EmitBranchable (ec, tests_end, false)){
if (right is Binary){
Binary right_binary = (Binary) right;
if (right_binary.EmitBranchable (ec, target, true)){
ig.MarkLabel (tests_end);
return true;
}
}
right.Emit (ec);
ig.Emit (OpCodes.Brtrue, target);
ig.MarkLabel (tests_end);
return true;
}
} else {
if (left_binary.EmitBranchable (ec, target, false)){
if (right is Binary){
Binary right_binary = (Binary) right;
if (right_binary.EmitBranchable (ec, target, false))
return true;
}
right.Emit (ec);
if (onTrue)
ig.Emit (OpCodes.Brtrue, target);
else
ig.Emit (OpCodes.Brfalse, target);
return true;
}
}
//
// Give up, and let the regular Emit work, but we could
// also optimize the left-non-Branchable, but-right-Branchable
//
}
return false;
} else if (oper == Operator.LogicalOr){
if (left is Binary){
Binary left_binary = (Binary) left;
if (onTrue){
if (left_binary.EmitBranchable (ec, target, true)){
if (right is Binary){
Binary right_binary = (Binary) right;
if (right_binary.EmitBranchable (ec, target, true))
return true;
}
right.Emit (ec);
ig.Emit (OpCodes.Brtrue, target);
return true;
}
//
// Give up, and let the regular Emit work, but we could
// also optimize the left-non-Branchable, but-right-Branchable
//
} else {
Label tests_end = ig.DefineLabel ();
if (left_binary.EmitBranchable (ec, tests_end, true)){
if (right is Binary){
Binary right_binary = (Binary) right;
if (right_binary.EmitBranchable (ec, target, false)){
ig.MarkLabel (tests_end);
return true;
}
}
right.Emit (ec);
ig.Emit (OpCodes.Brfalse, target);
ig.MarkLabel (tests_end);
return true;
}
}
}
return false;
} else if (!(oper == Operator.LessThan ||
oper == Operator.GreaterThan ||
oper == Operator.LessThanOrEqual ||
oper == Operator.GreaterThanOrEqual))
return false;
left.Emit (ec);
right.Emit (ec);
bool isUnsigned = is_unsigned (left.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:
return false;
}
return true;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
Type l = left.Type;
Type r = right.Type;
OpCode opcode;
if (method != null) {
// Note that operators are static anyway
if (Arguments != null)
Invocation.EmitArguments (ec, method, Arguments);
if (method is MethodInfo)
ig.Emit (OpCodes.Call, (MethodInfo) method);
else
ig.Emit (OpCodes.Call, (ConstructorInfo) method);
if (DelegateOperation)
ig.Emit (OpCodes.Castclass, type);
return;
}
//
// Handle short-circuit operators differently
// than the rest
//
if (oper == Operator.LogicalAnd){
Label load_zero = ig.DefineLabel ();
Label end = ig.DefineLabel ();
bool process = true;
if (left is Binary){
Binary left_binary = (Binary) left;
if (left_binary.EmitBranchable (ec, load_zero, false)){
right.Emit (ec);
ig.Emit (OpCodes.Br, end);
process = false;
}
}
if (process){
left.Emit (ec);
ig.Emit (OpCodes.Brfalse, load_zero);
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 ();
bool process = true;
if (left is Binary){
Binary left_binary = (Binary) left;
if (left_binary.EmitBranchable (ec, load_one, true)){
right.Emit (ec);
ig.Emit (OpCodes.Br, end);
process = false;
}
}
if (process){
left.Emit (ec);
ig.Emit (OpCodes.Brtrue, load_one);
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:
if (isUnsigned || (left.Type == TypeManager.float_type || left.Type == TypeManager.double_type))
ig.Emit (OpCodes.Cgt_Un);
else
ig.Emit (OpCodes.Cgt);
ig.Emit (OpCodes.Ldc_I4_0);
opcode = OpCodes.Ceq;
break;
case Operator.GreaterThanOrEqual:
if (isUnsigned || (left.Type == TypeManager.float_type || left.Type == TypeManager.double_type))
ig.Emit (OpCodes.Clt_Un);
else
ig.Emit (OpCodes.Clt);
ig.Emit (OpCodes.Ldc_I4_1);
opcode = OpCodes.Sub;
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);
}
public bool IsBuiltinOperator {
get {
return method == null;
}
}
}
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;
eclass = ExprClass.Variable;
this.loc = loc;
left = l;
right = r;
is_add = is_addition;
}
public override Expression DoResolve (EmitContext ec)
{
//
// We are born fully resolved
//
return this;
}
public override void Emit (EmitContext ec)
{
Type op_type = left.Type;
ILGenerator ig = ec.ig;
int size = GetTypeSize (op_type.GetElementType ());
if (right.Type.IsPointer){
//
// handle (pointer - pointer)
//
left.Emit (ec);
right.Emit (ec);
ig.Emit (OpCodes.Sub);
if (size != 1){
if (size == 0)
ig.Emit (OpCodes.Sizeof, op_type);
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);
right.Emit (ec);
if (size != 1){
if (size == 0)
ig.Emit (OpCodes.Sizeof, op_type);
else
IntLiteral.EmitInt (ig, size);
ig.Emit (OpCodes.Mul);
}
if (is_add)
ig.Emit (OpCodes.Add);
else
ig.Emit (OpCodes.Sub);
}
}
}
/// <summary>
/// Implements the ternary conditional operator (?:)
/// </summary>
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 (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;
if (trueExpr is NullLiteral){
type = false_type;
return this;
} else if (falseExpr is NullLiteral){
type = true_type;
return this;
}
//
// First, if an implicit conversion exists from trueExpr
// to falseExpr, then the result type is of type falseExpr.Type
//
conv = ConvertImplicit (ec, trueExpr, false_type, loc);
if (conv != null){
//
// Check if both can convert implicitl to each other's type
//
if (ConvertImplicit (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 = ConvertImplicit(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;
}
}
if (expr is BoolConstant){
BoolConstant bc = (BoolConstant) expr;
if (bc.Value)
return trueExpr;
else
return falseExpr;
}
return this;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
Label false_target = ig.DefineLabel ();
Label end_target = ig.DefineLabel ();
Statement.EmitBoolExpression (ec, expr, false_target, false);
trueExpr.Emit (ec);
ig.Emit (OpCodes.Br, end_target);
ig.MarkLabel (false_target);
falseExpr.Emit (ec);
ig.MarkLabel (end_target);
}
}
/// <summary>
/// Local variables
/// </summary>
public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
public readonly string Name;
public readonly Block Block;
VariableInfo variable_info;
bool is_readonly;
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,
VariableInfo variable_info, bool is_readonly)
: this (block, name, l)
{
this.variable_info = variable_info;
this.is_readonly = is_readonly;
}
public VariableInfo VariableInfo {
get {
if (variable_info == null) {
variable_info = Block.GetVariableInfo (Name);
is_readonly = variable_info.ReadOnly;
}
return variable_info;
}
}
public bool IsAssigned (EmitContext ec, Location loc)
{
return VariableInfo.IsAssigned (ec, loc);
}
public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
{
return VariableInfo.IsFieldAssigned (ec, name, loc);
}
public void SetAssigned (EmitContext ec)
{
VariableInfo.SetAssigned (ec);
}
public void SetFieldAssigned (EmitContext ec, string name)
{
VariableInfo.SetFieldAssigned (ec, name);
}
public bool IsReadOnly {
get {
if (variable_info == null) {
variable_info = Block.GetVariableInfo (Name);
is_readonly = variable_info.ReadOnly;
}
return is_readonly;
}
}
public override Expression DoResolve (EmitContext ec)
{
VariableInfo vi = VariableInfo;
Expression e;
e = Block.GetConstantExpression (Name);
if (e != null) {
vi.Used = true;
type = vi.VariableType;
eclass = ExprClass.Value;
return e;
}
if (ec.DoFlowAnalysis && !IsAssigned (ec, loc))
return null;
type = vi.VariableType;
return this;
}
override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
VariableInfo vi = VariableInfo;
if (ec.DoFlowAnalysis)
ec.SetVariableAssigned (vi);
Expression e = DoResolve (ec);
if (e == null)
return null;
if (is_readonly){
Error (1604, "cannot assign to `" + Name + "' because it is readonly");
return null;
}
return this;
}
public override void Emit (EmitContext ec)
{
VariableInfo vi = VariableInfo;
ILGenerator ig = ec.ig;
ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
vi.Used = true;
}
public void EmitAssign (EmitContext ec, Expression source)
{
ILGenerator ig = ec.ig;
VariableInfo vi = VariableInfo;
vi.Assigned = true;
source.Emit (ec);
ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
VariableInfo vi = VariableInfo;
ec.ig.Emit (OpCodes.Ldloca, vi.LocalBuilder);
}
}
/// <summary>
/// This represents a reference to a parameter in the intermediate
/// representation.
/// </summary>
public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
Parameters pars;
String name;
int idx;
public Parameter.Modifier mod;
public bool is_ref, is_out;
public ParameterReference (Parameters pars, int idx, string name, Location loc)
{
this.pars = pars;
this.idx = idx;
this.name = name;
this.loc = loc;
eclass = ExprClass.Variable;
}
public bool IsAssigned (EmitContext ec, Location loc)
{
if (!is_out || !ec.DoFlowAnalysis)
return true;
if (!ec.CurrentBranching.IsParameterAssigned (idx)) {
Report.Error (165, loc,
"Use of unassigned local variable `" + name + "'");
return false;
}
return true;
}
public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
{
if (!is_out || !ec.DoFlowAnalysis)
return true;
if (ec.CurrentBranching.IsParameterAssigned (idx))
return true;
if (!ec.CurrentBranching.IsParameterAssigned (idx, field_name)) {
Report.Error (170, loc,
"Use of possibly unassigned field `" + field_name + "'");
return false;
}
return true;
}
public void SetAssigned (EmitContext ec)
{
if (is_out && ec.DoFlowAnalysis)
ec.CurrentBranching.SetParameterAssigned (idx);
}
public void SetFieldAssigned (EmitContext ec, string field_name)
{
if (is_out && ec.DoFlowAnalysis)
ec.CurrentBranching.SetParameterAssigned (idx, field_name);
}
//
// 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)
{
type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
is_out = (mod & Parameter.Modifier.OUT) != 0;
eclass = ExprClass.Variable;
if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
return null;
return this;
}
override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
is_out = (mod & Parameter.Modifier.OUT) != 0;
eclass = ExprClass.Variable;
if (is_out && ec.DoFlowAnalysis)
ec.SetParameterAssigned (idx);
return this;
}
static 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.IsStatic)
arg_idx++;
EmitLdArg (ig, arg_idx);
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
int arg_idx = idx;
if (!ec.IsStatic)
arg_idx++;
EmitLdArg (ig, arg_idx);
if (!is_ref)
return;
//
// If we are a reference, we loaded on the stack a pointer
// Now lets load the real value
//
LoadFromPtr (ig, type);
}
public void EmitAssign (EmitContext ec, Expression source)
{
ILGenerator ig = ec.ig;
int arg_idx = idx;
if (!ec.IsStatic)
arg_idx++;
if (is_ref)
EmitLdArg (ig, arg_idx);
source.Emit (ec);
if (is_ref)
StoreFromPtr (ig, type);
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)
{
int arg_idx = idx;
if (!ec.IsStatic)
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);
}
}
}
/// <summary>
/// Used for arguments to New(), Invocation()
/// </summary>
public class Argument {
public enum AType : byte {
Expression,
Ref,
Out
};
public readonly AType ArgType;
public Expression Expr;
public Argument (Expression expr, AType type)
{
this.Expr = expr;
this.ArgType = type;
}
public Type Type {
get {
if (ArgType == AType.Ref || ArgType == AType.Out)
return TypeManager.LookupType (Expr.Type.ToString () + "&");
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)
{
return (a.ArgType == AType.Ref ? "ref " :
(a.ArgType == AType.Out ? "out " : "")) +
TypeManager.CSharpName (a.Expr.Type);
}
public bool ResolveMethodGroup (EmitContext ec, Location loc)
{
// 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;
}
public bool Resolve (EmitContext ec, Location loc)
{
if (ArgType == AType.Ref) {
Expr = Expr.Resolve (ec);
if (Expr == null)
return false;
Expr = Expr.ResolveLValue (ec, Expr);
} else if (ArgType == AType.Out)
Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
else
Expr = Expr.Resolve (ec);
if (Expr == null)
return false;
if (ArgType == AType.Expression)
return true;
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 {
Report.Error (
1510, loc,
"An lvalue is required as an argument to out or ref");
}
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.is_ref)
pr.EmitLoad (ec);
else {
pr.AddressOf (ec, mode);
}
} else
((IMemoryLocation)Expr).AddressOf (ec, mode);
} else
Expr.Emit (ec);
}
}
/// <summary>
/// Invocation of methods or delegates.
/// </summary>
public class Invocation : ExpressionStatement {
public readonly ArrayList Arguments;
Expression expr;
MethodBase method = null;
bool is_base;
static Hashtable method_parameter_cache;
static Invocation ()
{
method_parameter_cache = new PtrHashtable ();
}
//
// 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;
}
}
/// <summary>
/// Returns the Parameters (a ParameterData interface) for the
/// Method `mb'
/// </summary>
public static ParameterData GetParameterData (MethodBase mb)
{
object pd = method_parameter_cache [mb];
object ip;
if (pd != null)
return (ParameterData) pd;
ip = TypeManager.LookupParametersByBuilder (mb);
if (ip != null){
method_parameter_cache [mb] = ip;
return (ParameterData) ip;
} else {
ParameterInfo [] pi = mb.GetParameters ();
ReflectionParameters rp = new ReflectionParameters (pi);
method_parameter_cache [mb] = rp;
return (ParameterData) rp;
}
}
/// <summary>
/// Determines "better conversion" as specified in 7.4.2.3
/// Returns : 1 if a->p is better
/// 0 if a->q or neither is better
/// </summary>
static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
{
Type argument_type = a.Type;
Expression argument_expr = a.Expr;
if (argument_type == null)
throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
//
// This is a special case since csc behaves this way. I can't find
// it anywhere in the spec but oh well ...
//
if (argument_expr is NullLiteral && p == TypeManager.string_type && q == TypeManager.object_type)
return 1;
else if (argument_expr is NullLiteral && p == TypeManager.object_type && q == TypeManager.string_type)
return 0;
if (p == q)
return 0;
if (argument_type == p)
return 1;
if (argument_type == q)
return 0;
//
// Now probe whether an implicit constant expression conversion
// can be used.
//
// An implicit constant expression conversion permits the following
// conversions:
//
// * A constant-expression of type `int' can be converted to type
// sbyte, byute, short, ushort, uint, ulong provided the value of
// of the expression is withing the range of the destination type.
//
// * A constant-expression of type long can be converted to type
// ulong, provided the value of the constant expression is not negative
//
// FIXME: Note that this assumes that constant folding has
// taken place. We dont do constant folding yet.
//
if (argument_expr is IntConstant){
IntConstant ei = (IntConstant) argument_expr;
int value = ei.Value;
if (p == TypeManager.sbyte_type){
if (value >= SByte.MinValue && value <= SByte.MaxValue)
return 1;
} else if (p == TypeManager.byte_type){
if (q == TypeManager.sbyte_type &&
value >= SByte.MinValue && value <= SByte.MaxValue)
return 0;
else if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
return 1;
} else if (p == TypeManager.short_type){
if (value >= Int16.MinValue && value <= Int16.MaxValue)
return 1;
} else if (p == TypeManager.ushort_type){
if (q == TypeManager.short_type &&
value >= Int16.MinValue && value <= Int16.MaxValue)
return 0;
else if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
return 1;
} else if (p == TypeManager.int32_type){
if (value >= Int32.MinValue && value <= Int32.MaxValue)
return 1;
} else if (p == TypeManager.uint32_type){
//
// we can optimize this case: a positive int32
// always fits on a uint32
//
if (value >= 0)
return 1;
} else if (p == TypeManager.uint64_type){
//
// we can optimize this case: a positive int32
// always fits on a uint64
//
if (q == TypeManager.int64_type)
return 0;
else if (value >= 0)
return 1;
} else if (p == TypeManager.int64_type){
return 1;
}
} else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
LongConstant lc = (LongConstant) argument_expr;
if (p == TypeManager.uint64_type){
if (lc.Value > 0)
return 1;
}
}
if (q == null) {
Expression tmp = ConvertImplicit (ec, argument_expr, p, loc);
if (tmp != null)
return 1;
else
return 0;
}
Expression p_tmp = new EmptyExpression (p);
Expression q_tmp = new EmptyExpression (q);
if (ImplicitConversionExists (ec, p_tmp, q) == true &&
ImplicitConversionExists (ec, q_tmp, p) == false)
return 1;
if (p == TypeManager.sbyte_type)
if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
q == TypeManager.uint32_type || q == TypeManager.uint64_type)
return 1;
if (p == TypeManager.short_type)
if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
q == TypeManager.uint64_type)
return 1;
if (p == TypeManager.int32_type)
if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
return 1;
if (p == TypeManager.int64_type)
if (q == TypeManager.uint64_type)
return 1;
return 0;
}
/// <summary>
/// Determines "Better function"
/// </summary>
/// <remarks>
/// and returns an integer indicating :
/// 0 if candidate ain't better
/// 1 if candidate is better than the current best match
/// </remarks>
static int BetterFunction (EmitContext ec, ArrayList args,
MethodBase candidate, MethodBase best,
bool expanded_form, Location loc)
{
ParameterData candidate_pd = GetParameterData (candidate);
ParameterData best_pd;
int argument_count;
if (args == null)
argument_count = 0;
else
argument_count = args.Count;
int cand_count = candidate_pd.Count;
if (cand_count == 0 && argument_count == 0)
return 1;
if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
if (cand_count != argument_count)
return 0;
if (best == null) {
int x = 0;
if (argument_count == 0 && cand_count == 1 &&
candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
return 1;
for (int j = argument_count; j > 0;) {
j--;
Argument a = (Argument) args [j];
Type t = candidate_pd.ParameterType (j);
if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
if (expanded_form)
t = t.GetElementType ();
x = BetterConversion (ec, a, t, null, loc);
if (x <= 0)
break;
}
if (x > 0)
return 1;
else
return 0;
}
best_pd = GetParameterData (best);
int rating1 = 0, rating2 = 0;
for (int j = 0; j < argument_count; ++j) {
int x, y;
Argument a = (Argument) args [j];
Type ct = candidate_pd.ParameterType (j);
Type bt = best_pd.ParameterType (j);
if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
if (expanded_form)
ct = ct.GetElementType ();
if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
if (expanded_form)
bt = bt.GetElementType ();
x = BetterConversion (ec, a, ct, bt, loc);
y = BetterConversion (ec, a, bt, ct, loc);
if (x < y)
return 0;
rating1 += x;
rating2 += y;
}
if (rating1 > rating2)
return 1;
else
return 0;
}
public static string FullMethodDesc (MethodBase mb)
{
string ret_type = "";
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 = 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 l in left_set.Methods){
foreach (MethodBase r in right_set.Methods){
if (l != r)
continue;
common.Add (r);
break;
}
}
miset = new MemberInfo [length1 + length2 - common.Count];
left_set.Methods.CopyTo (miset, 0);
int k = length1;
foreach (MemberInfo mi in right_set.Methods){
if (!common.Contains (mi))
miset [k++] = mi;
}
union = new MethodGroupExpr (miset, loc);
return union;
}
/// <summary>
/// Determines is the candidate method, if a params method, is applicable
/// in its expanded form to the given set of arguments
/// </summary>
static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
{
int arg_count;
if (arguments == null)
arg_count = 0;
else
arg_count = arguments.Count;
ParameterData pd = GetParameterData (candidate);
int pd_count = pd.Count;
if (pd_count == 0)
return false;
if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
return false;
if (pd_count - 1 > 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 < pd_count - 1; ++i) {
Argument a = (Argument) arguments [i];
Parameter.Modifier a_mod = a.GetParameterModifier () &
~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
Parameter.Modifier p_mod = pd.ParameterModifier (i) &
~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
if (a_mod == p_mod) {
if (a_mod == Parameter.Modifier.NONE)
if (!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.LookupType (pt.FullName + "&");
if (pt != a.Type)
return false;
}
} else
return false;
}
Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
for (int i = pd_count - 1; i < arg_count; i++) {
Argument a = (Argument) arguments [i];
if (!StandardConversionExists (a.Expr, element_type))
return false;
}
return true;
}
/// <summary>
/// Determines if the candidate method is applicable (section 14.4.2.1)
/// to the given set of arguments
/// </summary>
static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
{
int arg_count;
if (arguments == null)
arg_count = 0;
else
arg_count = arguments.Count;
ParameterData pd = GetParameterData (candidate);
int pd_count = pd.Count;
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 () &
~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
Parameter.Modifier p_mod = pd.ParameterModifier (i) &
~(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 (!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.LookupType (pt.FullName + "&");
if (pt != a.Type)
return false;
}
} else
return false;
}
return true;
}
/// <summary>
/// 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.
///
/// </summary>
public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
ArrayList Arguments, Location loc)
{
MethodBase method = null;
Type current_type = null;
int argument_count;
ArrayList candidates = new ArrayList ();
foreach (MethodBase candidate in me.Methods){
int x;
// If we're going one level higher in the class hierarchy, abort if
// we already found an applicable method.
if (candidate.DeclaringType != current_type) {
current_type = candidate.DeclaringType;
if (method != null)
break;
}
// Check if candidate is applicable (section 14.4.2.1)
if (!IsApplicable (ec, Arguments, candidate))
continue;
candidates.Add (candidate);
x = BetterFunction (ec, Arguments, candidate, method, false, loc);
if (x == 0)
continue;
method = candidate;
}
if (Arguments == null)
argument_count = 0;
else
argument_count = Arguments.Count;
//
// Now we see if we can find params functions, applicable in their expanded form
// since if they were applicable in their normal form, they would have been selected
// above anyways
//
bool chose_params_expanded = false;
if (method == null) {
candidates = new ArrayList ();
foreach (MethodBase candidate in me.Methods){
if (!IsParamsMethodApplicable (ec, Arguments, candidate))
continue;
candidates.Add (candidate);
int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
if (x == 0)
continue;
method = candidate;
chose_params_expanded = true;
}
}
if (method == null) {
//
// Okay so we have failed to find anything so we
// return by providing info about the closest match
//
for (int i = 0; i < me.Methods.Length; ++i) {
MethodBase c = (MethodBase) me.Methods [i];
ParameterData pd = GetParameterData (c);
if (pd.Count != argument_count)
continue;
VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
null, loc);
}
return null;
}
//
// Now chec