Nothing,
}
+ /// <remarks>
+ /// This is used to tell Resolve in which types of expressions we're
+ /// interested.
+ /// </remarks>
+ [Flags]
+ public enum ResolveFlags {
+ // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
+ VariableOrValue = 1,
+
+ // Returns a type expression.
+ Type = 2,
+
+ // Returns a method group.
+ MethodGroup = 4,
+
+ // Allows SimpleNames to be returned.
+ // This is used by MemberAccess to construct long names that can not be
+ // partially resolved (namespace-qualified names for example).
+ SimpleName = 8,
+
+ // Mask of all the expression class flags.
+ MaskExprClass = 15,
+
+ // Disable control flow analysis while resolving the expression.
+ // This is used when resolving the instance expression of a field expression.
+ DisableFlowAnalysis = 16
+ }
+
//
// This is just as a hint to AddressOf of what will be done with the
// address.
void AddressOf (EmitContext ec, AddressOp mode);
}
+ /// <summary>
+ /// This interface is implemented by variables
+ /// </summary>
+ public interface IVariable {
+ /// <summary>
+ /// Checks whether the variable has already been assigned at
+ /// the current position of the method's control flow and
+ /// reports an appropriate error message if not.
+ ///
+ /// If the variable is a struct, then this call checks whether
+ /// all of its fields (including all private ones) have been
+ /// assigned.
+ /// </summary>
+ bool IsAssigned (EmitContext ec, Location loc);
+
+ /// <summary>
+ /// Checks whether field `name' in this struct has been assigned.
+ /// </summary>
+ bool IsFieldAssigned (EmitContext ec, string name, Location loc);
+
+ /// <summary>
+ /// Tells the flow analysis code that the variable has already
+ /// been assigned at the current code position.
+ ///
+ /// If the variable is a struct, this call marks all its fields
+ /// (including private fields) as being assigned.
+ /// </summary>
+ void SetAssigned (EmitContext ec);
+
+ /// <summary>
+ /// Tells the flow analysis code that field `name' in this struct
+ /// has already been assigned atthe current code position.
+ /// </summary>
+ void SetFieldAssigned (EmitContext ec, string name);
+ }
+
+ /// <summary>
+ /// This interface denotes an expression which evaluates to a member
+ /// of a struct or a class.
+ /// </summary>
+ public interface IMemberExpr
+ {
+ /// <summary>
+ /// The name of this member.
+ /// </summary>
+ string Name {
+ get;
+ }
+
+ /// <summary>
+ /// Whether this is an instance member.
+ /// </summary>
+ bool IsInstance {
+ get;
+ }
+
+ /// <summary>
+ /// Whether this is a static member.
+ /// </summary>
+ bool IsStatic {
+ get;
+ }
+
+ /// <summary>
+ /// The type which declares this member.
+ /// </summary>
+ Type DeclaringType {
+ get;
+ }
+
+ /// <summary>
+ /// The instance expression associated with this member, if it's a
+ /// non-static member.
+ /// </summary>
+ Expression InstanceExpression {
+ get; set;
+ }
+ }
+
+ /// <summary>
+ /// Expression which resolves to a type.
+ /// </summary>
+ public interface ITypeExpression
+ {
+ /// <summary>
+ /// Resolve the expression, but only lookup types.
+ /// </summary>
+ Expression DoResolveType (EmitContext ec);
+ }
+
/// <remarks>
/// Base class for expressions
/// </remarks>
public abstract class Expression {
public ExprClass eclass;
- protected Type type;
+ protected Type type;
+ protected Location loc;
public Type Type {
get {
}
}
+ public Location Location {
+ get {
+ return loc;
+ }
+ }
+
/// <summary>
/// Utility wrapper routine for Error, just to beautify the code
/// </summary>
- static protected void Error (int error, string s)
+ public void Error (int error, string s)
{
- Report.Error (error, s);
+ if (!Location.IsNull (loc))
+ Report.Error (error, loc, s);
+ else
+ Report.Error (error, s);
}
- static protected void Error (int error, Location loc, string s)
+ /// <summary>
+ /// Utility wrapper routine for Warning, just to beautify the code
+ /// </summary>
+ public void Warning (int warning, string s)
{
- Report.Error (error, loc, s);
+ if (!Location.IsNull (loc))
+ Report.Warning (warning, loc, s);
+ else
+ Report.Warning (warning, s);
}
-
+
/// <summary>
- /// Utility wrapper routine for Warning, just to beautify the code
+ /// Utility wrapper routine for Warning, only prints the warning if
+ /// warnings of level `level' are enabled.
/// </summary>
- static protected void Warning (int warning, string s)
+ public void Warning (int warning, int level, string s)
{
- Report.Warning (warning, s);
+ if (level <= RootContext.WarningLevel)
+ Warning (warning, s);
}
static public void Error_CannotConvertType (Location loc, Type source, Type target)
/// Currently Resolve wraps DoResolve to perform sanity
/// checking and assertion checking on what we expect from Resolve.
/// </remarks>
- public Expression Resolve (EmitContext ec)
+ public Expression Resolve (EmitContext ec, ResolveFlags flags)
{
- Expression e = DoResolve (ec);
-
- if (e != null){
-
- if (e is SimpleName){
- SimpleName s = (SimpleName) e;
+ // Are we doing a types-only search ?
+ if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type) {
+ ITypeExpression type_expr = this as ITypeExpression;
- Report.Error (
- 103, s.Location,
- "The name `" + s.Name + "' could not be found in `" +
- ec.DeclSpace.Name + "'");
+ if (type_expr == null)
return null;
- }
-
- if (e.eclass == ExprClass.Invalid)
- throw new Exception ("Expression " + e.GetType () +
- " ExprClass is Invalid after resolve");
- if (e.eclass != ExprClass.MethodGroup)
- if (e.type == null)
- throw new Exception (
- "Expression " + e.GetType () +
- " did not set its type after Resolve\n" +
- "called from: " + this.GetType ());
+ return type_expr.DoResolveType (ec);
}
- return e;
- }
+ bool old_do_flow_analysis = ec.DoFlowAnalysis;
+ if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
+ ec.DoFlowAnalysis = false;
- /// <summary>
- /// Performs expression resolution and semantic analysis, but
- /// allows SimpleNames to be returned.
- /// </summary>
- ///
- /// <remarks>
- /// This is used by MemberAccess to construct long names that can not be
- /// partially resolved (namespace-qualified names for example).
- /// </remarks>
- public Expression ResolveWithSimpleName (EmitContext ec)
- {
Expression e;
-
if (this is SimpleName)
e = ((SimpleName) this).DoResolveAllowStatic (ec);
else
e = DoResolve (ec);
- if (e != null){
- if (e is SimpleName)
- return e;
+ ec.DoFlowAnalysis = old_do_flow_analysis;
- if (e.eclass == ExprClass.Invalid)
- throw new Exception ("Expression " + e +
- " ExprClass is Invalid after resolve");
+ if (e == null)
+ return null;
+
+ if (e is SimpleName){
+ SimpleName s = (SimpleName) e;
+
+ if ((flags & ResolveFlags.SimpleName) == 0) {
+
+ object lookup = TypeManager.MemberLookup (
+ ec.ContainerType, ec.ContainerType, AllMemberTypes,
+ AllBindingFlags | BindingFlags.NonPublic, s.Name);
+ if (lookup != null)
+ Error (122, "`" + s.Name + "' " +
+ "is inaccessible because of its protection level");
+ else
+ Error (103, "The name `" + s.Name + "' could not be " +
+ "found in `" + ec.DeclSpace.Name + "'");
+ return null;
+ }
+
+ return s;
+ }
+
+ if ((e is TypeExpr) || (e is ComposedCast)) {
+ if ((flags & ResolveFlags.Type) == 0) {
+ e.Error118 (flags);
+ return null;
+ }
+
+ return e;
+ }
+
+ switch (e.eclass) {
+ case ExprClass.Type:
+ if ((flags & ResolveFlags.VariableOrValue) == 0) {
+ e.Error118 (flags);
+ return null;
+ }
+ break;
+
+ case ExprClass.MethodGroup:
+ if ((flags & ResolveFlags.MethodGroup) == 0) {
+ ((MethodGroupExpr) e).ReportUsageError ();
+ return null;
+ }
+ break;
+
+ case ExprClass.Value:
+ case ExprClass.Variable:
+ case ExprClass.PropertyAccess:
+ case ExprClass.EventAccess:
+ case ExprClass.IndexerAccess:
+ if ((flags & ResolveFlags.VariableOrValue) == 0) {
+ e.Error118 (flags);
+ return null;
+ }
+ break;
- if (e.eclass != ExprClass.MethodGroup)
- if (e.type == null)
- throw new Exception ("Expression " + e +
- " did not set its type after Resolve");
+ default:
+ throw new Exception ("Expression " + e.GetType () +
+ " ExprClass is Invalid after resolve");
}
+ if (e.type == null)
+ throw new Exception (
+ "Expression " + e.GetType () +
+ " did not set its type after Resolve\n" +
+ "called from: " + this.GetType ());
+
return e;
}
-
+
+ /// <summary>
+ /// Resolves an expression and performs semantic analysis on it.
+ /// </summary>
+ public Expression Resolve (EmitContext ec)
+ {
+ return Resolve (ec, ResolveFlags.VariableOrValue);
+ }
+
/// <summary>
/// Resolves an expression for LValue assignment
/// </summary>
SimpleName s = (SimpleName) e;
Report.Error (
- 103, s.Location,
+ 103, loc,
"The name `" + s.Name + "' could not be found in `" +
ec.DeclSpace.Name + "'");
return null;
throw new Exception ("Expression " + e +
" ExprClass is Invalid after resolve");
- if (e.eclass != ExprClass.MethodGroup)
- if (e.type == null)
- throw new Exception ("Expression " + e +
- " did not set its type after Resolve");
+ if (e.eclass == ExprClass.MethodGroup) {
+ ((MethodGroupExpr) e).ReportUsageError ();
+ return null;
+ }
+
+ if (e.type == null)
+ throw new Exception ("Expression " + e +
+ " did not set its type after Resolve");
}
return e;
return new ByteConstant ((byte)v);
else if (t == TypeManager.char_type)
return new CharConstant ((char)v);
+ else if (t == TypeManager.bool_type)
+ return new BoolConstant ((bool) v);
else if (TypeManager.IsEnumType (t)){
- Expression e = Constantify (v, v.GetType ());
+ Constant e = Constantify (v, TypeManager.TypeToCoreType (v.GetType ()));
- return new EnumConstant ((Constant) e, t);
+ return new EnumConstant (e, t);
} else
throw new Exception ("Unknown type for constant (" + t +
"), details: " + v);
else if (mi is PropertyInfo)
return new PropertyExpr ((PropertyInfo) mi, loc);
else if (mi is Type){
- return new TypeExpr ((System.Type) mi);
+ return new TypeExpr ((System.Type) mi, loc);
}
return null;
}
- //
- // Returns whether the array of memberinfos contains the given method
- //
- static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
- {
- Type [] new_args = TypeManager.GetArgumentTypes (new_method);
-
- foreach (MethodBase method in array){
- if (method.Name != new_method.Name)
- continue;
-
- Type [] old_args = TypeManager.GetArgumentTypes (method);
- int old_count = old_args.Length;
- int i;
-
- if (new_args.Length != old_count)
- continue;
-
- for (i = 0; i < old_count; i++){
- if (old_args [i] != new_args [i])
- break;
- }
- if (i != old_count)
- continue;
-
- if (!(method is MethodInfo && new_method is MethodInfo))
- return true;
-
- if (((MethodInfo) method).ReturnType == ((MethodInfo) new_method).ReturnType)
- return true;
- }
- return false;
- }
-
- //
- // We copy methods from `new_members' into `target_list' if the signature
- // for the method from in the new list does not exist in the target_list
- //
- // The name is assumed to be the same.
- //
- public static ArrayList CopyNewMethods (ArrayList target_list, MemberInfo [] new_members)
- {
- if (target_list == null){
- target_list = new ArrayList ();
-
- target_list.AddRange (new_members);
- return target_list;
- }
-
- MemberInfo [] target_array = new MemberInfo [target_list.Count];
- target_list.CopyTo (target_array, 0);
-
- foreach (MemberInfo mi in new_members){
- MethodBase new_method = (MethodBase) mi;
-
- if (!ArrayContainsMethod (target_array, new_method))
- target_list.Add (new_method);
- }
- return target_list;
- }
-
//
// FIXME: Probably implement a cache for (t,name,current_access_set)?
//
public static Expression MemberLookup (EmitContext ec, Type t, string name,
MemberTypes mt, BindingFlags bf, Location loc)
{
- Type source_type = ec.ContainerType;
-
- if (source_type != null){
- if (source_type == t || source_type.IsSubclassOf (t))
- bf |= BindingFlags.NonPublic;
- }
-
- //
- // Lookup for members starting in the type requested and going
- // up the hierarchy until a match is found.
- //
- // As soon as a non-method match is found, we return.
- //
- // If methods are found though, then the search proceeds scanning
- // for more public methods in the hierarchy with signatures that
- // do not match any of the signatures found so far.
- //
- ArrayList method_list = null;
- Type current_type = t;
- bool searching = true;
- do {
- MemberInfo [] mi;
-
- mi = TypeManager.FindMembers (
- current_type, mt, bf | BindingFlags.DeclaredOnly,
- System.Type.FilterName, name);
-
- if (current_type == TypeManager.object_type)
- searching = false;
- else {
- current_type = current_type.BaseType;
+ return MemberLookup (ec, ec.ContainerType, t, name, mt, bf, loc);
+ }
- //
- // This happens with interfaces, they have a null
- // basetype
- //
- if (current_type == null)
- searching = false;
- }
+ //
+ // Lookup type `t' for code in class `invocation_type'. Note that it's important
+ // to set `invocation_type' correctly since this method also checks whether the
+ // invoking class is allowed to access the member in class `t'. When you want to
+ // explicitly do a lookup in the base class, you must set both `t' and `invocation_type'
+ // to the base class (although a derived class can access protected members of its base
+ // class it cannot do so through an instance of the base class (error CS1540)).
+ //
- if (mi == null)
- continue;
-
- int count = mi.Length;
+ public static Expression MemberLookup (EmitContext ec, Type invocation_type, Type t,
+ string name, MemberTypes mt, BindingFlags bf,
+ Location loc)
+ {
+ MemberInfo [] mi = TypeManager.MemberLookup (invocation_type, t, mt, bf, name);
- if (count == 0)
- continue;
+ if (mi == null)
+ return null;
- //
- // Events are returned by both `static' and `instance'
- // searches, which means that our above FindMembers will
- // return two copies of the same.
- //
- if (count == 1 && !(mi [0] is MethodBase))
- return Expression.ExprClassFromMemberInfo (ec, mi [0], loc);
- if (count == 2 && (mi [0] is EventInfo))
- return Expression.ExprClassFromMemberInfo (ec, mi [0], loc);
+ int count = mi.Length;
- //
- // We found methods, turn the search into "method scan"
- // mode.
- //
- method_list = CopyNewMethods (method_list, mi);
- mt &= (MemberTypes.Method | MemberTypes.Constructor);
- } while (searching);
+ if (count > 1)
+ return new MethodGroupExpr (mi, loc);
- if (method_list != null && method_list.Count > 0)
- return new MethodGroupExpr (method_list);
+ if (mi [0] is MethodBase)
+ return new MethodGroupExpr (mi, loc);
- return null;
+ return ExprClassFromMemberInfo (ec, mi [0], loc);
}
public const MemberTypes AllMemberTypes =
public static Expression MemberLookup (EmitContext ec, Type t, string name, Location loc)
{
- return MemberLookup (ec, t, name, AllMemberTypes, AllBindingFlags, loc);
+ return MemberLookup (ec, ec.ContainerType, t, name,
+ AllMemberTypes, AllBindingFlags, loc);
+ }
+
+ public static Expression MethodLookup (EmitContext ec, Type t, string name, Location loc)
+ {
+ return MemberLookup (ec, ec.ContainerType, t, name,
+ MemberTypes.Method, AllBindingFlags, loc);
}
/// <summary>
/// </summary>
public static Expression MemberLookupFinal (EmitContext ec, Type t, string name,
Location loc)
+ {
+ return MemberLookupFinal (ec, t, name, MemberTypes.Method, AllBindingFlags, loc);
+ }
+
+ public static Expression MemberLookupFinal (EmitContext ec, Type t, string name,
+ MemberTypes mt, BindingFlags bf, Location loc)
{
Expression e;
- e = MemberLookup (ec, t, name, AllMemberTypes, AllBindingFlags, loc);
+ int errors = Report.Errors;
+
+ e = MemberLookup (ec, ec.ContainerType, t, name, mt, bf, loc);
if (e != null)
return e;
+
+ // Error has already been reported.
+ if (errors < Report.Errors)
+ return null;
e = MemberLookup (ec, t, name, AllMemberTypes,
AllBindingFlags | BindingFlags.NonPublic, loc);
return null;
}
+
+ static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
+ {
+ EventInfo ei = event_expr.EventInfo;
+
+ return TypeManager.GetPrivateFieldOfEvent (ei);
+ }
+ static EmptyExpression MyEmptyExpr;
static public Expression ImplicitReferenceConversion (Expression expr, Type target_type)
{
Type expr_type = expr.Type;
- if (target_type == TypeManager.object_type) {
+ if (expr_type == null && expr.eclass == ExprClass.MethodGroup){
+ // if we are a method group, emit a warning
+
+ expr.Emit (null);
+ }
+
+ //
+ // notice that it is possible to write "ValueType v = 1", the ValueType here
+ // is an abstract class, and not really a value type, so we apply the same rules.
+ //
+ if (target_type == TypeManager.object_type || target_type == TypeManager.value_type) {
//
// A pointer type cannot be converted to object
//
return new BoxedCast (expr);
if (expr_type.IsClass || expr_type.IsInterface)
return new EmptyCast (expr, target_type);
- } else if (expr_type.IsSubclassOf (target_type)) {
+ } else if (expr_type.IsSubclassOf (target_type))
return new EmptyCast (expr, target_type);
- } else {
+ else {
// This code is kind of mirrored inside StandardConversionExists
// with the small distinction that we only probe there
return new EmptyCast (expr, target_type);
// from any class-type S to any interface-type T.
- if (expr_type.IsClass && target_type.IsInterface) {
- if (TypeManager.ImplementsInterface (expr_type, target_type))
- return new EmptyCast (expr, target_type);
- else
- return null;
+ if (target_type.IsInterface) {
+ if (TypeManager.ImplementsInterface (expr_type, target_type)){
+ if (expr_type.IsClass)
+ return new EmptyCast (expr, target_type);
+ else if (expr_type.IsValueType)
+ return new BoxedCast (expr);
+ }
}
// from any interface type S to interface-type T.
if (expr_type.IsInterface && target_type.IsInterface) {
-
if (TypeManager.ImplementsInterface (expr_type, target_type))
return new EmptyCast (expr, target_type);
else
return null;
}
- /// <summary>
- /// Handles expressions like this: decimal d; d = 1;
- /// and changes them into: decimal d; d = new System.Decimal (1);
- /// </summary>
- static Expression InternalTypeConstructor (EmitContext ec, Expression expr, Type target)
- {
- ArrayList args = new ArrayList ();
-
- args.Add (new Argument (expr, Argument.AType.Expression));
-
- Expression ne = new New (target.FullName, args,
- new Location (-1));
-
- return ne.Resolve (ec);
- }
-
/// <summary>
/// Implicit Numeric Conversions.
///
return new ULongConstant ((ulong) v);
}
- //
- // If we have an enumeration, extract the underlying type,
- // use this during the comparission, but wrap around the original
- // target_type
- //
- Type real_target_type = target_type;
-
- if (TypeManager.IsEnumType (real_target_type))
- real_target_type = TypeManager.EnumToUnderlying (real_target_type);
+ Type real_target_type = target_type;
- if (expr_type == real_target_type)
- return new EmptyCast (expr, target_type);
-
if (expr_type == TypeManager.sbyte_type){
//
// From sbyte to short, int, long, float, double.
return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
if (real_target_type == TypeManager.short_type)
return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
- if (real_target_type == TypeManager.decimal_type)
- return InternalTypeConstructor (ec, expr, target_type);
} else if (expr_type == TypeManager.byte_type){
//
// From byte to short, ushort, int, uint, long, ulong, float, double
return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
if (real_target_type == TypeManager.double_type)
return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
- if (real_target_type == TypeManager.decimal_type)
- return InternalTypeConstructor (ec, expr, target_type);
} else if (expr_type == TypeManager.short_type){
//
// From short to int, long, float, double
return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
if (real_target_type == TypeManager.float_type)
return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
- if (real_target_type == TypeManager.decimal_type)
- return InternalTypeConstructor (ec, expr, target_type);
} else if (expr_type == TypeManager.ushort_type){
//
// From ushort to int, uint, long, ulong, float, double
return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
if (real_target_type == TypeManager.float_type)
return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
- if (real_target_type == TypeManager.decimal_type)
- return InternalTypeConstructor (ec, expr, target_type);
} else if (expr_type == TypeManager.int32_type){
//
// From int to long, float, double
return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
if (real_target_type == TypeManager.float_type)
return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
- if (real_target_type == TypeManager.decimal_type)
- return InternalTypeConstructor (ec, expr, target_type);
} else if (expr_type == TypeManager.uint32_type){
//
// From uint to long, ulong, float, double
if (real_target_type == TypeManager.float_type)
return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
OpCodes.Conv_R4);
- if (real_target_type == TypeManager.decimal_type)
- return InternalTypeConstructor (ec, expr, target_type);
- } else if ((expr_type == TypeManager.uint64_type) ||
- (expr_type == TypeManager.int64_type)){
+ } else if (expr_type == TypeManager.int64_type){
//
// From long/ulong to float, double
//
+ if (real_target_type == TypeManager.double_type)
+ return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
+ if (real_target_type == TypeManager.float_type)
+ return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
+ } else if (expr_type == TypeManager.uint64_type){
+ //
+ // From ulong to float, double
+ //
if (real_target_type == TypeManager.double_type)
return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
OpCodes.Conv_R8);
if (real_target_type == TypeManager.float_type)
return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
OpCodes.Conv_R4);
- if (real_target_type == TypeManager.decimal_type)
- return InternalTypeConstructor (ec, expr, target_type);
} else if (expr_type == TypeManager.char_type){
//
// From char to ushort, int, uint, long, ulong, float, double
return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
if (real_target_type == TypeManager.double_type)
return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
- if (real_target_type == TypeManager.decimal_type)
- return InternalTypeConstructor (ec, expr, target_type);
} else if (expr_type == TypeManager.float_type){
//
// float to double
return null;
}
+ //
+ // Tests whether an implicit reference conversion exists between expr_type
+ // and target_type
+ //
+ public static bool ImplicitReferenceConversionExists (Expression expr, Type target_type)
+ {
+ Type expr_type = expr.Type;
+
+ //
+ // This is the boxed case.
+ //
+ if (target_type == TypeManager.object_type) {
+ if ((expr_type.IsClass) ||
+ (expr_type.IsValueType) ||
+ (expr_type.IsInterface))
+ return true;
+
+ } else if (expr_type.IsSubclassOf (target_type)) {
+ return true;
+
+ } else {
+ // Please remember that all code below actually comes
+ // from ImplicitReferenceConversion so make sure code remains in sync
+
+ // from any class-type S to any interface-type T.
+ if (target_type.IsInterface) {
+ if (TypeManager.ImplementsInterface (expr_type, target_type))
+ return true;
+ }
+
+ // from any interface type S to interface-type T.
+ if (expr_type.IsInterface && target_type.IsInterface)
+ if (TypeManager.ImplementsInterface (expr_type, target_type))
+ return true;
+
+ // from an array-type S to an array-type of type T
+ if (expr_type.IsArray && target_type.IsArray) {
+ if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
+
+ Type expr_element_type = expr_type.GetElementType ();
+
+ if (MyEmptyExpr == null)
+ MyEmptyExpr = new EmptyExpression ();
+
+ MyEmptyExpr.SetType (expr_element_type);
+ Type target_element_type = target_type.GetElementType ();
+
+ if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
+ if (StandardConversionExists (MyEmptyExpr,
+ target_element_type))
+ return true;
+ }
+ }
+
+ // from an array-type to System.Array
+ if (expr_type.IsArray && (target_type == TypeManager.array_type))
+ return true;
+
+ // from any delegate type to System.Delegate
+ if (expr_type.IsSubclassOf (TypeManager.delegate_type) &&
+ target_type == TypeManager.delegate_type)
+ if (target_type.IsAssignableFrom (expr_type))
+ return true;
+
+ // from any array-type or delegate type into System.ICloneable.
+ if (expr_type.IsArray || expr_type.IsSubclassOf (TypeManager.delegate_type))
+ if (target_type == TypeManager.icloneable_type)
+ return true;
+
+ // from the null type to any reference-type.
+ if (expr is NullLiteral && !target_type.IsValueType &&
+ !TypeManager.IsEnumType (target_type))
+ return true;
+
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Same as StandardConversionExists except that it also looks at
+ /// implicit user defined conversions - needed for overload resolution
+ /// </summary>
+ public static bool ImplicitConversionExists (EmitContext ec, Expression expr, Type target_type)
+ {
+ if (StandardConversionExists (expr, target_type) == true)
+ return true;
+
+ Expression dummy = ImplicitUserConversion (ec, expr, target_type, Location.Null);
+
+ if (dummy != null)
+ return true;
+
+ return false;
+ }
+
/// <summary>
/// Determines if a standard implicit conversion exists from
/// expr_type to target_type
public static bool StandardConversionExists (Expression expr, Type target_type)
{
Type expr_type = expr.Type;
+
+ if (expr_type == TypeManager.void_type)
+ return false;
if (expr_type == target_type)
return true;
// First numeric conversions
-
+
if (expr_type == TypeManager.sbyte_type){
//
// From sbyte to short, int, long, float, double.
return true;
}
- // Next reference conversions
-
- if (target_type == TypeManager.object_type) {
- if ((expr_type.IsClass) ||
- (expr_type.IsValueType))
- return true;
-
- } else if (expr_type.IsSubclassOf (target_type)) {
+ if (ImplicitReferenceConversionExists (expr, target_type))
return true;
-
- } else {
- // Please remember that all code below actually comes
- // from ImplicitReferenceConversion so make sure code remains in sync
-
- // from any class-type S to any interface-type T.
- if (expr_type.IsClass && target_type.IsInterface) {
- if (TypeManager.ImplementsInterface (expr_type, target_type))
+
+ if (expr is IntConstant){
+ int value = ((IntConstant) expr).Value;
+
+ if (target_type == TypeManager.sbyte_type){
+ if (value >= SByte.MinValue && value <= SByte.MaxValue)
return true;
- }
-
- // from any interface type S to interface-type T.
- // FIXME : Is it right to use IsAssignableFrom ?
- if (expr_type.IsInterface && target_type.IsInterface)
- if (target_type.IsAssignableFrom (expr_type))
+ } else if (target_type == TypeManager.byte_type){
+ if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
return true;
-
- // from an array-type S to an array-type of type T
- if (expr_type.IsArray && target_type.IsArray) {
- if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
-
- Type expr_element_type = expr_type.GetElementType ();
-
- if (MyEmptyExpr == null)
- MyEmptyExpr = new EmptyExpression ();
-
- MyEmptyExpr.SetType (expr_element_type);
- Type target_element_type = target_type.GetElementType ();
-
- if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
- if (StandardConversionExists (MyEmptyExpr,
- target_element_type))
- return true;
- }
- }
-
- // from an array-type to System.Array
- if (expr_type.IsArray && target_type.IsAssignableFrom (expr_type))
- return true;
-
- // from any delegate type to System.Delegate
- if (expr_type.IsSubclassOf (TypeManager.delegate_type) &&
- target_type == TypeManager.delegate_type)
- if (target_type.IsAssignableFrom (expr_type))
+ } else if (target_type == TypeManager.short_type){
+ if (value >= Int16.MinValue && value <= Int16.MaxValue)
return true;
-
- // from any array-type or delegate type into System.ICloneable.
- if (expr_type.IsArray || expr_type.IsSubclassOf (TypeManager.delegate_type))
- if (target_type == TypeManager.icloneable_type)
+ } else if (target_type == TypeManager.ushort_type){
+ if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
+ return true;
+ } else if (target_type == TypeManager.uint32_type){
+ if (value >= 0)
return true;
+ } else if (target_type == TypeManager.uint64_type){
+ //
+ // we can optimize this case: a positive int32
+ // always fits on a uint64. But we need an opcode
+ // to do it.
+ //
+ if (value >= 0)
+ return true;
+ }
- // from the null type to any reference-type.
- if (expr is NullLiteral && !target_type.IsValueType)
+ if (value == 0 && expr is IntLiteral && TypeManager.IsEnumType (target_type))
return true;
-
}
+ if (expr is LongConstant && target_type == TypeManager.uint64_type){
+ //
+ // Try the implicit constant expression conversion
+ // from long to ulong, instead of a nice routine,
+ // we just inline it
+ //
+ long v = ((LongConstant) expr).Value;
+ if (v > 0)
+ return true;
+ }
+
+ if (target_type.IsSubclassOf (TypeManager.enum_type) && expr is IntLiteral){
+ IntLiteral i = (IntLiteral) expr;
+
+ if (i.Value == 0)
+ return true;
+ }
+
+ if (target_type == TypeManager.void_ptr_type && expr_type.IsPointer)
+ return true;
+
return false;
}
- static EmptyExpression MyEmptyExpr;
+ //
+ // Used internally by FindMostEncompassedType, this is used
+ // to avoid creating lots of objects in the tight loop inside
+ // FindMostEncompassedType
+ //
+ static EmptyExpression priv_fmet_param;
+
/// <summary>
- /// Tells whether an implicit conversion exists from expr_type to
- /// target_type
+ /// Finds "most encompassed type" according to the spec (13.4.2)
+ /// amongst the methods in the MethodGroupExpr
/// </summary>
- public bool ImplicitConversionExists (EmitContext ec, Type expr_type, Type target_type,
- Location l)
+ static Type FindMostEncompassedType (ArrayList types)
{
- if (MyEmptyExpr == null)
- MyEmptyExpr = new EmptyExpression (expr_type);
- else
- MyEmptyExpr.SetType (expr_type);
+ Type best = null;
+
+ if (priv_fmet_param == null)
+ priv_fmet_param = new EmptyExpression ();
- return ConvertImplicit (ec, MyEmptyExpr, target_type, l) != null;
+ foreach (Type t in types){
+ priv_fmet_param.SetType (t);
+
+ if (best == null) {
+ best = t;
+ continue;
+ }
+
+ if (StandardConversionExists (priv_fmet_param, best))
+ best = t;
+ }
+
+ return best;
}
+
+ //
+ // Used internally by FindMostEncompassingType, this is used
+ // to avoid creating lots of objects in the tight loop inside
+ // FindMostEncompassingType
+ //
+ static EmptyExpression priv_fmee_ret;
/// <summary>
- /// Finds "most encompassed type" according to the spec (13.4.2)
- /// amongst the methods in the MethodGroupExpr which convert from a
- /// type encompassing source_type
+ /// Finds "most encompassing type" according to the spec (13.4.2)
+ /// amongst the types in the given set
/// </summary>
- static Type FindMostEncompassedType (MethodGroupExpr me, Type source_type)
+ static Type FindMostEncompassingType (ArrayList types)
{
Type best = null;
+
+ if (priv_fmee_ret == null)
+ priv_fmee_ret = new EmptyExpression ();
+
+ foreach (Type t in types){
+ priv_fmee_ret.SetType (best);
+
+ if (best == null) {
+ best = t;
+ continue;
+ }
+
+ if (StandardConversionExists (priv_fmee_ret, t))
+ best = t;
+ }
+
+ return best;
+ }
+
+ //
+ // Used to avoid creating too many objects
+ //
+ static EmptyExpression priv_fms_expr;
+
+ /// <summary>
+ /// Finds the most specific source Sx according to the rules of the spec (13.4.4)
+ /// by making use of FindMostEncomp* methods. Applies the correct rules separately
+ /// for explicit and implicit conversion operators.
+ /// </summary>
+ static public Type FindMostSpecificSource (MethodGroupExpr me, Expression source,
+ bool apply_explicit_conv_rules,
+ Location loc)
+ {
+ ArrayList src_types_set = new ArrayList ();
- for (int i = me.Methods.Length; i > 0; ) {
- i--;
+ if (priv_fms_expr == null)
+ priv_fms_expr = new EmptyExpression ();
- MethodBase mb = me.Methods [i];
+ //
+ // If any operator converts from S then Sx = S
+ //
+ Type source_type = source.Type;
+ foreach (MethodBase mb in me.Methods){
ParameterData pd = Invocation.GetParameterData (mb);
Type param_type = pd.ParameterType (0);
- Expression source = new EmptyExpression (source_type);
- Expression param = new EmptyExpression (param_type);
+ if (param_type == source_type)
+ return param_type;
- if (StandardConversionExists (source, param_type)) {
- if (best == null)
- best = param_type;
-
- if (StandardConversionExists (param, best))
- best = param_type;
+ if (apply_explicit_conv_rules) {
+ //
+ // From the spec :
+ // Find the set of applicable user-defined conversion operators, U. This set
+ // consists of the
+ // user-defined implicit or explicit conversion operators declared by
+ // the classes or structs in D that convert from a type encompassing
+ // or encompassed by S to a type encompassing or encompassed by T
+ //
+ priv_fms_expr.SetType (param_type);
+ if (StandardConversionExists (priv_fms_expr, source_type))
+ src_types_set.Add (param_type);
+ else {
+ if (StandardConversionExists (source, param_type))
+ src_types_set.Add (param_type);
+ }
+ } else {
+ //
+ // Only if S is encompassed by param_type
+ //
+ if (StandardConversionExists (source, param_type))
+ src_types_set.Add (param_type);
}
}
+
+ //
+ // Explicit Conv rules
+ //
+ if (apply_explicit_conv_rules) {
+ ArrayList candidate_set = new ArrayList ();
- return best;
+ foreach (Type param_type in src_types_set){
+ if (StandardConversionExists (source, param_type))
+ candidate_set.Add (param_type);
+ }
+
+ if (candidate_set.Count != 0)
+ return FindMostEncompassedType (candidate_set);
+ }
+
+ //
+ // Final case
+ //
+ if (apply_explicit_conv_rules)
+ return FindMostEncompassingType (src_types_set);
+ else
+ return FindMostEncompassedType (src_types_set);
}
+
+ //
+ // Useful in avoiding proliferation of objects
+ //
+ static EmptyExpression priv_fmt_expr;
/// <summary>
- /// Finds "most encompassing type" according to the spec (13.4.2)
- /// amongst the methods in the MethodGroupExpr which convert to a
- /// type encompassed by target_type
+ /// Finds the most specific target Tx according to section 13.4.4
/// </summary>
- static Type FindMostEncompassingType (MethodGroupExpr me, Type target)
+ static public Type FindMostSpecificTarget (MethodGroupExpr me, Type target,
+ bool apply_explicit_conv_rules,
+ Location loc)
{
- Type best = null;
+ ArrayList tgt_types_set = new ArrayList ();
- for (int i = me.Methods.Length; i > 0; ) {
- i--;
-
- MethodInfo mi = (MethodInfo) me.Methods [i];
+ if (priv_fmt_expr == null)
+ priv_fmt_expr = new EmptyExpression ();
+
+ //
+ // If any operator converts to T then Tx = T
+ //
+ foreach (MethodInfo mi in me.Methods){
Type ret_type = mi.ReturnType;
- Expression ret = new EmptyExpression (ret_type);
-
- if (StandardConversionExists (ret, target)) {
- if (best == null)
- best = ret_type;
+ if (ret_type == target)
+ return ret_type;
- if (!StandardConversionExists (ret, best))
- best = ret_type;
+ if (apply_explicit_conv_rules) {
+ //
+ // From the spec :
+ // Find the set of applicable user-defined conversion operators, U.
+ //
+ // This set consists of the
+ // user-defined implicit or explicit conversion operators declared by
+ // the classes or structs in D that convert from a type encompassing
+ // or encompassed by S to a type encompassing or encompassed by T
+ //
+ priv_fms_expr.SetType (ret_type);
+ if (StandardConversionExists (priv_fms_expr, target))
+ tgt_types_set.Add (ret_type);
+ else {
+ priv_fms_expr.SetType (target);
+ if (StandardConversionExists (priv_fms_expr, ret_type))
+ tgt_types_set.Add (ret_type);
+ }
+ } else {
+ //
+ // Only if T is encompassed by param_type
+ //
+ priv_fms_expr.SetType (ret_type);
+ if (StandardConversionExists (priv_fms_expr, target))
+ tgt_types_set.Add (ret_type);
}
-
}
-
- return best;
+ //
+ // Explicit conv rules
+ //
+ if (apply_explicit_conv_rules) {
+ ArrayList candidate_set = new ArrayList ();
+
+ foreach (Type ret_type in tgt_types_set){
+ priv_fmt_expr.SetType (ret_type);
+
+ if (StandardConversionExists (priv_fmt_expr, target))
+ candidate_set.Add (ret_type);
+ }
+
+ if (candidate_set.Count != 0)
+ return FindMostEncompassingType (candidate_set);
+ }
+
+ //
+ // Okay, final case !
+ //
+ if (apply_explicit_conv_rules)
+ return FindMostEncompassedType (tgt_types_set);
+ else
+ return FindMostEncompassingType (tgt_types_set);
}
-
/// <summary>
/// User-defined Implicit conversions
/// </summary>
{
return UserDefinedConversion (ec, source, target, loc, true);
}
-
+
/// <summary>
- /// User-defined conversions
+ /// Computes the MethodGroup for the user-defined conversion
+ /// operators from source_type to target_type. `look_for_explicit'
+ /// controls whether we should also include the list of explicit
+ /// operators
/// </summary>
- static public Expression UserDefinedConversion (EmitContext ec, Expression source,
- Type target, Location loc,
- bool look_for_explicit)
+ static MethodGroupExpr GetConversionOperators (EmitContext ec,
+ Type source_type, Type target_type,
+ Location loc, bool look_for_explicit)
{
- Expression mg1 = null, mg2 = null, mg3 = null, mg4 = null;
+ Expression mg1 = null, mg2 = null;
Expression mg5 = null, mg6 = null, mg7 = null, mg8 = null;
- Expression e;
- MethodBase method = null;
- Type source_type = source.Type;
-
string op_name;
-
- // If we have a boolean type, we need to check for the True operator
+ //
// FIXME : How does the False operator come into the picture ?
- // FIXME : This doesn't look complete and very correct !
- if (target == TypeManager.bool_type)
+ // This doesn't look complete and very correct !
+ //
+ if (target_type == TypeManager.bool_type && !look_for_explicit)
op_name = "op_True";
else
op_name = "op_Implicit";
-
- mg1 = MemberLookup (ec, source_type, op_name, loc);
- if (source_type.BaseType != null)
- mg2 = MemberLookup (ec, source_type.BaseType, op_name, loc);
+ MethodGroupExpr union3;
- mg3 = MemberLookup (ec, target, op_name, loc);
+ mg1 = MethodLookup (ec, source_type, op_name, loc);
+ if (source_type.BaseType != null)
+ mg2 = MethodLookup (ec, source_type.BaseType, op_name, loc);
- if (target.BaseType != null)
- mg4 = MemberLookup (ec, target.BaseType, op_name, loc);
+ if (mg1 == null)
+ union3 = (MethodGroupExpr) mg2;
+ else if (mg2 == null)
+ union3 = (MethodGroupExpr) mg1;
+ else
+ union3 = Invocation.MakeUnionSet (mg1, mg2, loc);
- MethodGroupExpr union1 = Invocation.MakeUnionSet (mg1, mg2);
- MethodGroupExpr union2 = Invocation.MakeUnionSet (mg3, mg4);
+ mg1 = MethodLookup (ec, target_type, op_name, loc);
+ if (mg1 != null){
+ if (union3 != null)
+ union3 = Invocation.MakeUnionSet (union3, mg1, loc);
+ else
+ union3 = (MethodGroupExpr) mg1;
+ }
- MethodGroupExpr union3 = Invocation.MakeUnionSet (union1, union2);
+ if (target_type.BaseType != null)
+ mg1 = MethodLookup (ec, target_type.BaseType, op_name, loc);
+
+ if (mg1 != null){
+ if (union3 != null)
+ union3 = Invocation.MakeUnionSet (union3, mg1, loc);
+ else
+ union3 = (MethodGroupExpr) mg1;
+ }
MethodGroupExpr union4 = null;
if (look_for_explicit) {
-
op_name = "op_Explicit";
-
- mg5 = MemberLookup (ec, source_type, op_name, loc);
+ mg5 = MemberLookup (ec, source_type, op_name, loc);
if (source_type.BaseType != null)
- mg6 = MemberLookup (ec, source_type.BaseType, op_name, loc);
+ mg6 = MethodLookup (ec, source_type.BaseType, op_name, loc);
- mg7 = MemberLookup (ec, target, op_name, loc);
+ mg7 = MemberLookup (ec, target_type, op_name, loc);
+ if (target_type.BaseType != null)
+ mg8 = MethodLookup (ec, target_type.BaseType, op_name, loc);
- if (target.BaseType != null)
- mg8 = MemberLookup (ec, target.BaseType, op_name, loc);
-
- MethodGroupExpr union5 = Invocation.MakeUnionSet (mg5, mg6);
- MethodGroupExpr union6 = Invocation.MakeUnionSet (mg7, mg8);
+ MethodGroupExpr union5 = Invocation.MakeUnionSet (mg5, mg6, loc);
+ MethodGroupExpr union6 = Invocation.MakeUnionSet (mg7, mg8, loc);
- union4 = Invocation.MakeUnionSet (union5, union6);
+ union4 = Invocation.MakeUnionSet (union5, union6, loc);
}
- MethodGroupExpr union = Invocation.MakeUnionSet (union3, union4);
+ return Invocation.MakeUnionSet (union3, union4, loc);
+ }
+
+ /// <summary>
+ /// User-defined conversions
+ /// </summary>
+ static public Expression UserDefinedConversion (EmitContext ec, Expression source,
+ Type target, Location loc,
+ bool look_for_explicit)
+ {
+ MethodGroupExpr union;
+ Type source_type = source.Type;
+ MethodBase method = null;
+
+ union = GetConversionOperators (ec, source_type, target, loc, look_for_explicit);
+ if (union == null)
+ return null;
+
+ Type most_specific_source, most_specific_target;
- if (union != null) {
+#if BLAH
+ foreach (MethodBase m in union.Methods){
+ Console.WriteLine ("Name: " + m.Name);
+ Console.WriteLine (" : " + ((MethodInfo)m).ReturnType);
+ }
+#endif
+
+ most_specific_source = FindMostSpecificSource (union, source, look_for_explicit, loc);
+ if (most_specific_source == null)
+ return null;
- Type most_specific_source, most_specific_target;
+ most_specific_target = FindMostSpecificTarget (union, target, look_for_explicit, loc);
+ if (most_specific_target == null)
+ return null;
- most_specific_source = FindMostEncompassedType (union, source_type);
- if (most_specific_source == null)
- return null;
+ int count = 0;
- most_specific_target = FindMostEncompassingType (union, target);
- if (most_specific_target == null)
- return null;
-
- int count = 0;
+ foreach (MethodBase mb in union.Methods){
+ ParameterData pd = Invocation.GetParameterData (mb);
+ MethodInfo mi = (MethodInfo) mb;
- for (int i = union.Methods.Length; i > 0;) {
- i--;
-
- MethodBase mb = union.Methods [i];
- ParameterData pd = Invocation.GetParameterData (mb);
- MethodInfo mi = (MethodInfo) union.Methods [i];
-
- if (pd.ParameterType (0) == most_specific_source &&
- mi.ReturnType == most_specific_target) {
- method = mb;
- count++;
- }
+ if (pd.ParameterType (0) == most_specific_source &&
+ mi.ReturnType == most_specific_target) {
+ method = mb;
+ count++;
}
-
- if (method == null || count > 1) {
- Report.Error (-11, loc, "Ambiguous user defined conversion");
- return null;
- }
-
- //
- // This will do the conversion to the best match that we
- // found. Now we need to perform an implict standard conversion
- // if the best match was not the type that we were requested
- // by target.
- //
- if (look_for_explicit)
- source = ConvertExplicitStandard (ec, source, most_specific_source, loc);
- else
- source = ConvertImplicitStandard (ec, source,
- most_specific_source, loc);
-
- if (source == null)
- return null;
-
- e = new UserCast ((MethodInfo) method, source);
-
- if (e.Type != target){
- if (!look_for_explicit)
- e = ConvertImplicitStandard (ec, e, target, loc);
- else
- e = ConvertExplicitStandard (ec, e, target, loc);
-
- return e;
- } else
- return e;
}
- return null;
+ if (method == null || count > 1) {
+ Report.Error (-11, loc, "Ambiguous user defined conversion");
+ return null;
+ }
+
+ //
+ // This will do the conversion to the best match that we
+ // found. Now we need to perform an implict standard conversion
+ // if the best match was not the type that we were requested
+ // by target.
+ //
+ if (look_for_explicit)
+ source = ConvertExplicitStandard (ec, source, most_specific_source, loc);
+ else
+ source = ConvertImplicitStandard (ec, source, most_specific_source, loc);
+
+ if (source == null)
+ return null;
+
+ Expression e;
+ e = new UserCast ((MethodInfo) method, source, loc);
+ if (e.Type != target){
+ if (!look_for_explicit)
+ e = ConvertImplicitStandard (ec, e, target, loc);
+ else
+ e = ConvertExplicitStandard (ec, e, target, loc);
+ }
+ return e;
}
/// <summary>
return new ULongConstant ((ulong) value);
}
- if (value == 0 && ic is IntLiteral && TypeManager.IsEnumType (target_type))
- return new EnumConstant (ic, target_type);
-
+ if (value == 0 && ic is IntLiteral && TypeManager.IsEnumType (target_type)){
+ Type underlying = TypeManager.EnumToUnderlying (target_type);
+ Constant e = (Constant) ic;
+
+ //
+ // Possibly, we need to create a different 0 literal before passing
+ // to EnumConstant
+ //n
+ if (underlying == TypeManager.int64_type)
+ e = new LongLiteral (0);
+ else if (underlying == TypeManager.uint64_type)
+ e = new ULongLiteral (0);
+
+ return new EnumConstant (e, target_type);
+ }
return null;
}
TypeManager.CSharpName (source) + "' to `" +
TypeManager.CSharpName (target) + "'";
- Error (29, loc, msg);
+ Report.Error (29, loc, msg);
}
/// <summary>
return e;
if (source is DoubleLiteral && target_type == TypeManager.float_type){
- Error (664, loc,
- "Double literal cannot be implicitly converted to " +
- "float type, use F suffix to create a float literal");
+ Report.Error (664, loc,
+ "Double literal cannot be implicitly converted to " +
+ "float type, use F suffix to create a float literal");
}
-
+
Error_CannotConvertImplicit (loc, source.Type, target_type);
return null;
/// <summary>
/// Performs the explicit numeric conversions
/// </summary>
- static Expression ConvertNumericExplicit (EmitContext ec, Expression expr,
- Type target_type)
+ static Expression ConvertNumericExplicit (EmitContext ec, Expression expr, Type target_type, Location loc)
{
Type expr_type = expr.Type;
//
// If we have an enumeration, extract the underlying type,
- // use this during the comparission, but wrap around the original
+ // use this during the comparison, but wrap around the original
// target_type
//
Type real_target_type = target_type;
if (TypeManager.IsEnumType (real_target_type))
real_target_type = TypeManager.EnumToUnderlying (real_target_type);
+ if (StandardConversionExists (expr, real_target_type)){
+ Expression ce = ConvertImplicitStandard (ec, expr, real_target_type, loc);
+
+ if (real_target_type != target_type)
+ return new EmptyCast (ce, target_type);
+ return ce;
+ }
+
if (expr_type == TypeManager.sbyte_type){
//
// From sbyte to byte, ushort, uint, ulong, char
return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U8);
if (real_target_type == TypeManager.char_type)
return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_CH);
- if (real_target_type == TypeManager.decimal_type)
- return InternalTypeConstructor (ec, expr, target_type);
} else if (expr_type == TypeManager.double_type){
//
// From double to byte, byte, short,
return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_CH);
if (real_target_type == TypeManager.float_type)
return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_R4);
- if (real_target_type == TypeManager.decimal_type)
- return InternalTypeConstructor (ec, expr, target_type);
}
// decimal is taken care of by the op_Explicit methods.
/// Returns whether an explicit reference conversion can be performed
/// from source_type to target_type
/// </summary>
- static bool ExplicitReferenceConversionExists (Type source_type, Type target_type)
+ public static bool ExplicitReferenceConversionExists (Type source_type, Type target_type)
{
bool target_is_value_type = target_type.IsValueType;
}
//
- // From any class type S to any interface T, provides S is not sealed
+ // From any class type S to any interface T, provided S is not sealed
// and provided S does not implement T.
//
if (target_type.IsInterface && !source_type.IsSealed &&
- !target_type.IsAssignableFrom (source_type))
+ !TypeManager.ImplementsInterface (source_type, target_type))
return true;
//
// sealed, or provided T implements S.
//
if (source_type.IsInterface &&
- (!target_type.IsSealed || source_type.IsAssignableFrom (target_type)))
+ (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type)))
return true;
-
+
+
// From an array type S with an element type Se to an array type T with an
// element type Te provided all the following are true:
// * S and T differe only in element type, in other words, S and T
// From System.Array to any array-type
if (source_type == TypeManager.array_type &&
- target_type.IsSubclassOf (TypeManager.array_type)){
+ target_type.IsArray){
return true;
}
{
Type source_type = source.Type;
bool target_is_value_type = target_type.IsValueType;
-
+
//
// From object to any reference type
//
// and provided S does not implement T.
//
if (target_type.IsInterface && !source_type.IsSealed) {
-
if (TypeManager.ImplementsInterface (source_type, target_type))
return null;
else
// sealed, or provided T implements S.
//
if (source_type.IsInterface) {
-
- if (target_type.IsSealed)
- return null;
-
- if (TypeManager.ImplementsInterface (target_type, source_type))
+ if (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type))
return new ClassCast (source, target_type);
else
return null;
// From System.Array to any array-type
if (source_type == TypeManager.array_type &&
- target_type.IsSubclassOf (TypeManager.array_type)){
+ target_type.IsArray) {
return new ClassCast (source, target_type);
}
if (ne != null)
return ne;
- ne = ConvertNumericExplicit (ec, expr, target_type);
+ ne = ConvertNumericExplicit (ec, expr, target_type, loc);
if (ne != null)
return ne;
if (t != null)
return t;
- return ConvertNumericExplicit (ec, e, target_type);
+ t = ConvertNumericExplicit (ec, e, target_type, loc);
+ if (t != null)
+ return t;
+
+ Error_CannotConvertType (loc, expr_type, target_type);
+ return null;
}
ne = ConvertReferenceExplicit (expr, target_type);
if (ci != null)
return ci;
- ce = ConvertNumericExplicit (ec, e, target_type);
+ ce = ConvertNumericExplicit (ec, e, target_type, loc);
if (ce != null)
return ce;
//
}
/// <summary>
- /// Same as ConverExplicit, only it doesn't include user defined conversions
+ /// Same as ConvertExplicit, only it doesn't include user defined conversions
/// </summary>
static public Expression ConvertExplicitStandard (EmitContext ec, Expression expr,
Type target_type, Location l)
if (ne != null)
return ne;
- ne = ConvertNumericExplicit (ec, expr, target_type);
+ ne = ConvertNumericExplicit (ec, expr, target_type, l);
if (ne != null)
return ne;
/// <summary>
/// Reports that we were expecting `expr' to be of class `expected'
/// </summary>
- protected void report118 (Location loc, Expression expr, string expected)
+ public void Error118 (string expected)
{
string kind = "Unknown";
- if (expr != null)
- kind = ExprClassName (expr.eclass);
+ kind = ExprClassName (eclass);
- Error (118, loc, "Expression denotes a `" + kind +
+ Error (118, "Expression denotes a `" + kind +
"' where a `" + expected + "' was expected");
}
+ public void Error118 (ResolveFlags flags)
+ {
+ ArrayList valid = new ArrayList (10);
+
+ if ((flags & ResolveFlags.VariableOrValue) != 0) {
+ valid.Add ("variable");
+ valid.Add ("value");
+ }
+
+ if ((flags & ResolveFlags.Type) != 0)
+ valid.Add ("type");
+
+ if ((flags & ResolveFlags.MethodGroup) != 0)
+ valid.Add ("method group");
+
+ if ((flags & ResolveFlags.SimpleName) != 0)
+ valid.Add ("simple name");
+
+ if (valid.Count == 0)
+ valid.Add ("unknown");
+
+ StringBuilder sb = new StringBuilder ();
+ for (int i = 0; i < valid.Count; i++) {
+ if (i > 0)
+ sb.Append (", ");
+ else if (i == valid.Count)
+ sb.Append (" or ");
+ sb.Append (valid [i]);
+ }
+
+ string kind = ExprClassName (eclass);
+
+ Error (119, "Expression denotes a `" + kind + "' where " +
+ "a `" + sb.ToString () + "' was expected");
+ }
+
static void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
{
Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
}
//
- // Load the object from the pointer. The `IsReference' is used
- // to control whether we should use Ldind_Ref or LdObj if the
- // value is not a `core' type.
+ // Load the object from the pointer.
//
- // Maybe we should try to extract this infromation form the type?
- // TODO: Maybe this is a bug. The reason we have this flag is because
- // I had almost identical code in ParameterReference (for handling
- // references) and in UnboxCast.
- //
- public static void LoadFromPtr (ILGenerator ig, Type t, bool IsReference)
+ public static void LoadFromPtr (ILGenerator ig, Type t)
{
if (t == TypeManager.int32_type)
ig.Emit (OpCodes.Ldind_I4);
ig.Emit (OpCodes.Ldind_I1);
else if (t == TypeManager.intptr_type)
ig.Emit (OpCodes.Ldind_I);
- else if (TypeManager.IsEnumType (t)){
- LoadFromPtr (ig, TypeManager.EnumToUnderlying (t), IsReference);
- } else {
- if (IsReference)
+ else if (TypeManager.IsEnumType (t)) {
+ if (t == TypeManager.enum_type)
ig.Emit (OpCodes.Ldind_Ref);
- else
- ig.Emit (OpCodes.Ldobj, t);
- }
+ else
+ LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
+ } else if (t.IsValueType)
+ ig.Emit (OpCodes.Ldobj, t);
+ else
+ ig.Emit (OpCodes.Ldind_Ref);
}
//
//
public static void StoreFromPtr (ILGenerator ig, Type type)
{
+ if (TypeManager.IsEnumType (type))
+ type = TypeManager.EnumToUnderlying (type);
if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
ig.Emit (OpCodes.Stind_I4);
else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
ig.Emit (OpCodes.Stind_I1);
else if (type == TypeManager.intptr_type)
ig.Emit (OpCodes.Stind_I);
+ else if (type.IsValueType)
+ ig.Emit (OpCodes.Stobj, type);
else
ig.Emit (OpCodes.Stind_Ref);
}
//
public static int GetTypeSize (Type t)
{
+ t = TypeManager.TypeToCoreType (t);
if (t == TypeManager.int32_type ||
t == TypeManager.uint32_type ||
t == TypeManager.float_type)
t == TypeManager.char_type ||
t == TypeManager.ushort_type)
return 2;
+ else if (t == TypeManager.decimal_type)
+ return 16;
else
return 0;
}
+
+ //
+ // Default implementation of IAssignMethod.CacheTemporaries
+ //
+ public void CacheTemporaries (EmitContext ec)
+ {
+ }
+
+ static void Error_NegativeArrayIndex (Location loc)
+ {
+ Report.Error (284, loc, "Can not create array with a negative size");
+ }
+
+ //
+ // Converts `source' to an int, uint, long or ulong.
+ //
+ public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
+ {
+ Expression target;
+
+ bool old_checked = ec.CheckState;
+ ec.CheckState = true;
+
+ target = ConvertImplicit (ec, source, TypeManager.int32_type, loc);
+ if (target == null){
+ target = ConvertImplicit (ec, source, TypeManager.uint32_type, loc);
+ if (target == null){
+ target = ConvertImplicit (ec, source, TypeManager.int64_type, loc);
+ if (target == null){
+ target = ConvertImplicit (ec, source, TypeManager.uint64_type, loc);
+ if (target == null)
+ Expression.Error_CannotConvertImplicit (loc, source.Type, TypeManager.int32_type);
+ }
+ }
+ }
+ ec.CheckState = old_checked;
+
+ //
+ // Only positive constants are allowed at compile time
+ //
+ if (target is Constant){
+ if (target is IntConstant){
+ if (((IntConstant) target).Value < 0){
+ Error_NegativeArrayIndex (loc);
+ return null;
+ }
+ }
+
+ if (target is LongConstant){
+ if (((LongConstant) target).Value < 0){
+ Error_NegativeArrayIndex (loc);
+ return null;
+ }
+ }
+
+ }
+
+ return target;
+ }
+
}
/// <summary>
base.Emit (ec);
ig.Emit (OpCodes.Unbox, t);
- LoadFromPtr (ig, t, false);
+ LoadFromPtr (ig, t);
}
}
public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
: base (child, return_type)
{
- mode = m;
checked_state = ec.CheckState;
+ mode = m;
}
public override Expression DoResolve (EmitContext ec)
/// The downside of this is that we might be hitting `LookupType' too many
/// times with this scheme.
/// </remarks>
- public class SimpleName : Expression {
+ public class SimpleName : Expression, ITypeExpression {
public readonly string Name;
- public readonly Location Location;
public SimpleName (string name, Location l)
{
Name = name;
- Location = l;
+ loc = l;
}
- public static void Error120 (Location l, string name)
+ public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
{
- Report.Error (
- 120, l,
- "An object reference is required " +
- "for the non-static field `"+name+"'");
+ if (ec.IsFieldInitializer)
+ Report.Error (
+ 236, l,
+ "A field initializer cannot reference the non-static field, " +
+ "method or property `"+name+"'");
+ else
+ Report.Error (
+ 120, l,
+ "An object reference is required " +
+ "for the non-static field `"+name+"'");
}
//
// Checks whether we are trying to access an instance
// property, method or field from a static body.
//
- Expression MemberStaticCheck (Expression e)
+ Expression MemberStaticCheck (EmitContext ec, Expression e)
{
- if (e is FieldExpr){
- FieldInfo fi = ((FieldExpr) e).FieldInfo;
+ if (e is IMemberExpr){
+ IMemberExpr member = (IMemberExpr) e;
- if (!fi.IsStatic){
- Error120 (Location, Name);
- return null;
- }
- } else if (e is MethodGroupExpr){
- MethodGroupExpr mg = (MethodGroupExpr) e;
-
- if (!mg.RemoveInstanceMethods ()){
- Error120 (Location, mg.Methods [0].Name);
- return null;
- }
- return e;
- } else if (e is PropertyExpr){
- if (!((PropertyExpr) e).IsStatic){
- Error120 (Location, Name);
- return null;
- }
- } else if (e is EventExpr) {
- if (!((EventExpr) e).IsStatic) {
- Error120 (Location, Name);
+ if (!member.IsStatic){
+ Error_ObjectRefRequired (ec, loc, Name);
return null;
}
}
public override Expression DoResolve (EmitContext ec)
{
- return SimpleNameResolve (ec, false);
+ return SimpleNameResolve (ec, null, false);
+ }
+
+ public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
+ {
+ return SimpleNameResolve (ec, right_side, false);
}
+
public Expression DoResolveAllowStatic (EmitContext ec)
{
- return SimpleNameResolve (ec, true);
+ return SimpleNameResolve (ec, null, true);
+ }
+
+ public Expression DoResolveType (EmitContext ec)
+ {
+ //
+ // Stage 3: Lookup symbol in the various namespaces.
+ //
+ DeclSpace ds = ec.DeclSpace;
+ Type t;
+ string alias_value;
+
+ if (ec.ResolvingTypeTree){
+ int errors = Report.Errors;
+ Type dt = ec.DeclSpace.FindType (loc, Name);
+ if (Report.Errors != errors)
+ return null;
+
+ if (dt != null)
+ return new TypeExpr (dt, loc);
+ }
+
+ if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
+ return new TypeExpr (t, loc);
+
+
+ //
+ // Stage 2 part b: Lookup up if we are an alias to a type
+ // or a namespace.
+ //
+ // Since we are cheating: we only do the Alias lookup for
+ // namespaces if the name does not include any dots in it
+ //
+
+ alias_value = ec.DeclSpace.LookupAlias (Name);
+
+ if (Name.IndexOf ('.') == -1 && alias_value != null) {
+ if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
+ return new TypeExpr (t, loc);
+
+ // we have alias value, but it isn't Type, so try if it's namespace
+ return new SimpleName (alias_value, loc);
+ }
+
+ // No match, maybe our parent can compose us
+ // into something meaningful.
+ return this;
}
/// <remarks>
/// Type is both an instance variable and a Type; Type.GetType
/// is the static method not an instance method of type.
/// </remarks>
- Expression SimpleNameResolve (EmitContext ec, bool allow_static)
+ Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static)
{
Expression e = null;
//
// Stage 1: Performed by the parser (binding to locals or parameters).
- //
- if (!ec.OnlyLookupTypes){
- Block current_block = ec.CurrentBlock;
- if (current_block != null && current_block.IsVariableDefined (Name)){
- LocalVariableReference var;
-
- var = new LocalVariableReference (ec.CurrentBlock, Name, Location);
-
- return var.Resolve (ec);
- }
-
- //
- // Stage 2: Lookup members
- //
-
- //
- // For enums, the TypeBuilder is not ec.TypeContainer.TypeBuilder
- // Hence we have two different cases
- //
- e = MemberLookup (ec, ec.DeclSpace.TypeBuilder, Name, Location);
-
- if (e == null && ec.TypeContainer.TypeBuilder != null)
- e = MemberLookup (ec, ec.TypeContainer.TypeBuilder, Name, Location);
- }
-
- // Continuation of stage 2
- if (e == null){
- //
- // Stage 3: Lookup symbol in the various namespaces.
- //
- DeclSpace ds = ec.DeclSpace;
- Type t;
- string alias_value;
-
- if ((t = RootContext.LookupType (ds, Name, true, Location)) != null)
- return new TypeExpr (t);
-
- //
- // Stage 2 part b: Lookup up if we are an alias to a type
- // or a namespace.
- //
- // Since we are cheating: we only do the Alias lookup for
- // namespaces if the name does not include any dots in it
- //
-
- if (Name.IndexOf ('.') == -1 && (alias_value = ec.TypeContainer.LookupAlias (Name)) != null) {
- // System.Console.WriteLine (Name + " --> " + alias_value);
- if ((t = RootContext.LookupType (ds, alias_value, true, Location))
- != null)
- return new TypeExpr (t);
-
- // we have alias value, but it isn't Type, so try if it's namespace
- return new SimpleName (alias_value, Location);
- }
-
- // No match, maybe our parent can compose us
- // into something meaningful.
- return this;
- }
-
- //
- // Stage 2 continues here.
- //
- if (e is TypeExpr)
- return e;
+ //
+ Block current_block = ec.CurrentBlock;
+ if (current_block != null && current_block.IsVariableDefined (Name)){
+ LocalVariableReference var;
- if (ec.OnlyLookupTypes)
- return null;
-
- if (e is FieldExpr){
- FieldExpr fe = (FieldExpr) e;
- FieldInfo fi = fe.FieldInfo;
+ var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
- if (fi.FieldType.IsPointer && !ec.InUnsafe){
- UnsafeError (Location);
- }
-
- if (ec.IsStatic){
- if (!allow_static && !fi.IsStatic){
- Error120 (Location, Name);
- return null;
- }
- } else {
- // If we are not in static code and this
- // field is not static, set the instance to `this'.
+ if (right_side != null)
+ return var.ResolveLValue (ec, right_side);
+ else
+ return var.Resolve (ec);
+ }
- if (!fi.IsStatic)
- fe.InstanceExpression = ec.This;
- }
+ if (current_block != null){
+ int idx = -1;
+ Parameter par = null;
+ Parameters pars = current_block.Parameters;
+ if (pars != null)
+ par = pars.GetParameterByName (Name, out idx);
-
- if (fi is FieldBuilder) {
- Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
+ if (par != null) {
+ ParameterReference param;
- if (c != null) {
- object o = c.LookupConstantValue (ec);
- object real_value = ((Constant)c.Expr).GetValue ();
- return Constantify (real_value, fi.FieldType);
- }
+ param = new ParameterReference (pars, idx, Name, loc);
+
+ if (right_side != null)
+ return param.ResolveLValue (ec, right_side);
+ else
+ return param.Resolve (ec);
}
+ }
- return e;
- }
+ //
+ // Stage 2: Lookup members
+ //
+
+ //
+ // For enums, the TypeBuilder is not ec.DeclSpace.TypeBuilder
+ // Hence we have two different cases
+ //
+
+ DeclSpace lookup_ds = ec.DeclSpace;
+ do {
+ if (lookup_ds.TypeBuilder == null)
+ break;
+
+ e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
+ if (e != null)
+ break;
- if (e is EventExpr) {
//
- // If the event is local to this class, we transform ourselves into
- // a FieldExpr
+ // Classes/structs keep looking, enums break
//
- EventExpr ee = (EventExpr) e;
+ if (lookup_ds is TypeContainer)
+ lookup_ds = ((TypeContainer) lookup_ds).Parent;
+ else
+ break;
+ } while (lookup_ds != null);
+
+ if (e == null && ec.ContainerType != null)
+ e = MemberLookup (ec, ec.ContainerType, Name, loc);
- Expression ml = MemberLookup (
- ec, ec.DeclSpace.TypeBuilder, ee.EventInfo.Name,
- MemberTypes.Event, AllBindingFlags, Location);
+ if (e == null)
+ return DoResolveType (ec);
- if (ml != null) {
- MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
+ if (e is TypeExpr)
+ return e;
- if (mi == null) {
- //
- // If this happens, then we have an event with its own
- // accessors and private field etc so there's no need
- // to transform ourselves : we should instead flag an error
- //
- Assign.error70 (ee.EventInfo, Location);
- return null;
- }
+ if (e is IMemberExpr) {
+ e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
+ if (e == null)
+ return null;
- ml = ExprClassFromMemberInfo (ec, mi, Location);
-
- if (ml == null) {
- Report.Error (-200, Location, "Internal error!!");
- return null;
- }
+ IMemberExpr me = e as IMemberExpr;
+ if (me == null)
+ return e;
- Expression instance_expr;
-
- FieldInfo fi = ((FieldExpr) ml).FieldInfo;
+ // This fails if ResolveMemberAccess() was unable to decide whether
+ // it's a field or a type of the same name.
+ if (!me.IsStatic && (me.InstanceExpression == null))
+ return e;
- if (fi.IsStatic)
- instance_expr = null;
- else
- instance_expr = ec.This;
+ if (!me.IsStatic &&
+ TypeManager.IsNestedChildOf (me.InstanceExpression.Type, me.DeclaringType)) {
+ Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
+ "outer type `" + me.DeclaringType + "' via nested type `" +
+ me.InstanceExpression.Type + "'");
+ return null;
+ }
- instance_expr = instance_expr.Resolve (ec);
+ if (right_side != null)
+ e = e.DoResolveLValue (ec, right_side);
+ else
+ e = e.DoResolve (ec);
- if (instance_expr != null)
- instance_expr = instance_expr.Resolve (ec);
-
- return MemberAccess.ResolveMemberAccess (ec, ml, instance_expr, Location, null);
- }
+ return e;
}
-
-
- if (ec.IsStatic){
+
+ if (ec.IsStatic || ec.IsFieldInitializer){
if (allow_static)
return e;
- return MemberStaticCheck (e);
+ return MemberStaticCheck (ec, e);
} else
return e;
}
-
+
public override void Emit (EmitContext ec)
{
//
// find the name as a namespace
//
- Error (103, Location, "The name `" + Name +
+ Error (103, "The name `" + Name +
"' does not exist in the class `" +
ec.DeclSpace.Name + "'");
}
+
+ public override string ToString ()
+ {
+ return Name;
+ }
}
/// <summary>
/// Fully resolved expression that evaluates to a type
/// </summary>
- public class TypeExpr : Expression {
- public TypeExpr (Type t)
+ public class TypeExpr : Expression, ITypeExpression {
+ public TypeExpr (Type t, Location l)
{
Type = t;
eclass = ExprClass.Type;
+ loc = l;
+ }
+
+ public virtual Expression DoResolveType (EmitContext ec)
+ {
+ return this;
}
override public Expression DoResolve (EmitContext ec)
override public void Emit (EmitContext ec)
{
- throw new Exception ("Implement me");
+ throw new Exception ("Should never be called");
+ }
+
+ public override string ToString ()
+ {
+ return Type.ToString ();
+ }
+ }
+
+ /// <summary>
+ /// Used to create types from a fully qualified name. These are just used
+ /// by the parser to setup the core types. A TypeLookupExpression is always
+ /// classified as a type.
+ /// </summary>
+ public class TypeLookupExpression : TypeExpr {
+ string name;
+
+ public TypeLookupExpression (string name) : base (null, Location.Null)
+ {
+ this.name = name;
+ }
+
+ public override Expression DoResolveType (EmitContext ec)
+ {
+ if (type == null)
+ type = RootContext.LookupType (ec.DeclSpace, name, false, Location.Null);
+ return this;
+ }
+
+ public override Expression DoResolve (EmitContext ec)
+ {
+ return DoResolveType (ec);
+ }
+
+ public override void Emit (EmitContext ec)
+ {
+ throw new Exception ("Should never be called");
+ }
+
+ public override string ToString ()
+ {
+ return name;
}
}
///
/// This is a fully resolved expression that evaluates to a type
/// </summary>
- public class MethodGroupExpr : Expression {
+ public class MethodGroupExpr : Expression, IMemberExpr {
public MethodBase [] Methods;
Expression instance_expression = null;
+ bool is_explicit_impl = false;
- public MethodGroupExpr (MemberInfo [] mi)
+ public MethodGroupExpr (MemberInfo [] mi, Location l)
{
Methods = new MethodBase [mi.Length];
mi.CopyTo (Methods, 0);
eclass = ExprClass.MethodGroup;
+ type = TypeManager.object_type;
+ loc = l;
}
- public MethodGroupExpr (ArrayList l)
+ public MethodGroupExpr (ArrayList list, Location l)
{
- Methods = new MethodBase [l.Count];
+ Methods = new MethodBase [list.Count];
try {
- l.CopyTo (Methods, 0);
+ list.CopyTo (Methods, 0);
} catch {
- foreach (MemberInfo m in l){
+ foreach (MemberInfo m in list){
if (!(m is MethodBase)){
Console.WriteLine ("Name " + m.Name);
Console.WriteLine ("Found a: " + m.GetType ().FullName);
}
throw;
}
+ loc = l;
eclass = ExprClass.MethodGroup;
+ type = TypeManager.object_type;
+ }
+
+ public Type DeclaringType {
+ get {
+ return Methods [0].DeclaringType;
+ }
}
//
instance_expression = value;
}
}
+
+ public bool IsExplicitImpl {
+ get {
+ return is_explicit_impl;
+ }
+
+ set {
+ is_explicit_impl = value;
+ }
+ }
+
+ public string Name {
+ get {
+ return Methods [0].Name;
+ }
+ }
+
+ public bool IsInstance {
+ get {
+ foreach (MethodBase mb in Methods)
+ if (!mb.IsStatic)
+ return true;
+
+ return false;
+ }
+ }
+
+ public bool IsStatic {
+ get {
+ foreach (MethodBase mb in Methods)
+ if (mb.IsStatic)
+ return true;
+
+ return false;
+ }
+ }
override public Expression DoResolve (EmitContext ec)
{
+ if (instance_expression != null) {
+ instance_expression = instance_expression.DoResolve (ec);
+ if (instance_expression == null)
+ return null;
+ }
+
return this;
}
+ public void ReportUsageError ()
+ {
+ Report.Error (654, loc, "Method `" + Methods [0].DeclaringType + "." +
+ Methods [0].Name + "()' is referenced without parentheses");
+ }
+
override public void Emit (EmitContext ec)
{
- throw new Exception ("This should never be reached");
+ ReportUsageError ();
}
bool RemoveMethods (bool keep_static)
{
ArrayList smethods = new ArrayList ();
- int top = Methods.Length;
- int i;
-
- for (i = 0; i < top; i++){
- MethodBase mb = Methods [i];
+ foreach (MethodBase mb in Methods){
if (mb.IsStatic == keep_static)
smethods.Add (mb);
}
/// <summary>
/// Fully resolved expression that evaluates to a Field
/// </summary>
- public class FieldExpr : Expression, IAssignMethod, IMemoryLocation {
+ public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr {
public readonly FieldInfo FieldInfo;
- public Expression InstanceExpression;
- Location loc;
+ Expression instance_expr;
public FieldExpr (FieldInfo fi, Location l)
{
loc = l;
}
+ public string Name {
+ get {
+ return FieldInfo.Name;
+ }
+ }
+
+ public bool IsInstance {
+ get {
+ return !FieldInfo.IsStatic;
+ }
+ }
+
+ public bool IsStatic {
+ get {
+ return FieldInfo.IsStatic;
+ }
+ }
+
+ public Type DeclaringType {
+ get {
+ return FieldInfo.DeclaringType;
+ }
+ }
+
+ public Expression InstanceExpression {
+ get {
+ return instance_expr;
+ }
+
+ set {
+ instance_expr = value;
+ }
+ }
+
override public Expression DoResolve (EmitContext ec)
{
if (!FieldInfo.IsStatic){
- if (InstanceExpression == null){
+ if (instance_expr == null){
throw new Exception ("non-static FieldExpr without instance var\n" +
"You have to assign the Instance variable\n" +
"Of the FieldExpr to set this\n");
}
- InstanceExpression = InstanceExpression.Resolve (ec);
- if (InstanceExpression == null)
+ // Resolve the field's instance expression while flow analysis is turned
+ // off: when accessing a field "a.b", we must check whether the field
+ // "a.b" is initialized, not whether the whole struct "a" is initialized.
+ instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
+ ResolveFlags.DisableFlowAnalysis);
+ if (instance_expr == null)
return null;
}
+ // If the instance expression is a local variable or parameter.
+ IVariable var = instance_expr as IVariable;
+ if ((var != null) && !var.IsFieldAssigned (ec, FieldInfo.Name, loc))
+ return null;
+
return this;
}
+ void Report_AssignToReadonly (bool is_instance)
+ {
+ string msg;
+
+ if (is_instance)
+ msg = "Readonly field can not be assigned outside " +
+ "of constructor or variable initializer";
+ else
+ msg = "A static readonly field can only be assigned in " +
+ "a static constructor";
+
+ Report.Error (is_instance ? 191 : 198, loc, msg);
+ }
+
override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
+ IVariable var = instance_expr as IVariable;
+ if (var != null)
+ var.SetFieldAssigned (ec, FieldInfo.Name);
+
Expression e = DoResolve (ec);
if (e == null)
if (ec.IsConstructor)
return this;
- Report.Error (191, loc,
- "Readonly field can not be assigned outside " +
- "of constructor or variable initializer");
+ Report_AssignToReadonly (true);
return null;
}
{
ILGenerator ig = ec.ig;
bool is_volatile = false;
-
+
if (FieldInfo is FieldBuilder){
- Field f = TypeManager.GetField (FieldInfo);
- if (f != null){
- if ((f.ModFlags & Modifiers.VOLATILE) != 0)
- is_volatile = true;
+ FieldBase f = TypeManager.GetField (FieldInfo);
+
+ if ((f.ModFlags & Modifiers.VOLATILE) != 0)
+ is_volatile = true;
- f.status |= Field.Status.USED;
- }
+ f.status |= Field.Status.USED;
}
if (FieldInfo.IsStatic){
ig.Emit (OpCodes.Ldsfld, FieldInfo);
} else {
- if (InstanceExpression.Type.IsValueType){
+ if (instance_expr.Type.IsValueType){
IMemoryLocation ml;
LocalTemporary tempo = null;
- if (!(InstanceExpression is IMemoryLocation)){
+ if (!(instance_expr is IMemoryLocation)){
tempo = new LocalTemporary (
- ec, InstanceExpression.Type);
+ ec, instance_expr.Type);
InstanceExpression.Emit (ec);
tempo.Store (ec);
ml = tempo;
} else
- ml = (IMemoryLocation) InstanceExpression;
+ ml = (IMemoryLocation) instance_expr;
ml.AddressOf (ec, AddressOp.Load);
} else
- InstanceExpression.Emit (ec);
+ instance_expr.Emit (ec);
if (is_volatile)
ig.Emit (OpCodes.Volatile);
public void EmitAssign (EmitContext ec, Expression source)
{
- bool is_static = FieldInfo.IsStatic;
+ FieldAttributes fa = FieldInfo.Attributes;
+ bool is_static = (fa & FieldAttributes.Static) != 0;
+ bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
ILGenerator ig = ec.ig;
+
+ if (is_readonly && !ec.IsConstructor){
+ Report_AssignToReadonly (!is_static);
+ return;
+ }
if (!is_static){
- Expression instance = InstanceExpression;
+ Expression instance = instance_expr;
if (instance.Type.IsValueType){
if (instance is IMemoryLocation){
source.Emit (ec);
if (FieldInfo is FieldBuilder){
- Field f = TypeManager.GetField (FieldInfo);
- if (f != null && (f.ModFlags & Modifiers.VOLATILE) != 0)
+ FieldBase f = TypeManager.GetField (FieldInfo);
+
+ if ((f.ModFlags & Modifiers.VOLATILE) != 0)
ig.Emit (OpCodes.Volatile);
}
ig.Emit (OpCodes.Stfld, FieldInfo);
if (FieldInfo is FieldBuilder){
- Field f = TypeManager.GetField (FieldInfo);
+ FieldBase f = TypeManager.GetField (FieldInfo);
f.status |= Field.Status.ASSIGNED;
}
ILGenerator ig = ec.ig;
if (FieldInfo is FieldBuilder){
- Field f = TypeManager.GetField (FieldInfo);
- if (f != null && (f.ModFlags & Modifiers.VOLATILE) != 0)
+ FieldBase f = TypeManager.GetField (FieldInfo);
+ if ((f.ModFlags & Modifiers.VOLATILE) != 0)
ig.Emit (OpCodes.Volatile);
}
if (FieldInfo is FieldBuilder){
- Field f = TypeManager.GetField (FieldInfo);
+ FieldBase f = TypeManager.GetField (FieldInfo);
if ((mode & AddressOp.Store) != 0)
f.status |= Field.Status.ASSIGNED;
// get the address of the copy.
//
if (FieldInfo.IsInitOnly){
- LocalBuilder local;
+ if (ec.IsConstructor) {
+ ig.Emit (OpCodes.Ldsflda, FieldInfo);
+ } else {
+ LocalBuilder local;
- Emit (ec);
- local = ig.DeclareLocal (type);
- ig.Emit (OpCodes.Stloc, local);
- ig.Emit (OpCodes.Ldloca, local);
+ Emit (ec);
+ local = ig.DeclareLocal (type);
+ ig.Emit (OpCodes.Stloc, local);
+ ig.Emit (OpCodes.Ldloca, local);
+ }
return;
- }
+ }
if (FieldInfo.IsStatic)
ig.Emit (OpCodes.Ldsflda, FieldInfo);
else {
- InstanceExpression.Emit (ec);
+ if (instance_expr is IMemoryLocation)
+ ((IMemoryLocation)instance_expr).AddressOf (ec, AddressOp.LoadStore);
+ else
+ instance_expr.Emit (ec);
ig.Emit (OpCodes.Ldflda, FieldInfo);
}
}
/// This is not an LValue because we need to re-write the expression, we
/// can not take data from the stack and store it.
/// </summary>
- public class PropertyExpr : ExpressionStatement, IAssignMethod {
+ public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
public readonly PropertyInfo PropertyInfo;
- public readonly bool IsStatic;
public bool IsBase;
MethodInfo [] Accessors;
- Location loc;
+ bool is_static;
Expression instance_expr;
-
+
public PropertyExpr (PropertyInfo pi, Location l)
{
PropertyInfo = pi;
eclass = ExprClass.PropertyAccess;
- IsStatic = false;
+ is_static = false;
loc = l;
Accessors = TypeManager.GetAccessors (pi);
if (Accessors != null)
- for (int i = 0; i < Accessors.Length; i++){
- if (Accessors [i] != null)
- if (Accessors [i].IsStatic)
- IsStatic = true;
+ foreach (MethodInfo mi in Accessors){
+ if (mi != null)
+ if (mi.IsStatic)
+ is_static = true;
}
else
Accessors = new MethodInfo [2];
- type = pi.PropertyType;
+ type = TypeManager.TypeToCoreType (pi.PropertyType);
+ }
+
+ public string Name {
+ get {
+ return PropertyInfo.Name;
+ }
+ }
+
+ public bool IsInstance {
+ get {
+ return !is_static;
+ }
+ }
+
+ public bool IsStatic {
+ get {
+ return is_static;
+ }
+ }
+
+ public Type DeclaringType {
+ get {
+ return PropertyInfo.DeclaringType;
+ }
}
//
return null;
}
- type = PropertyInfo.PropertyType;
+ if ((instance_expr == null) && ec.IsStatic && !is_static) {
+ SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
+ return null;
+ }
+
+ if (instance_expr != null) {
+ instance_expr = instance_expr.DoResolve (ec);
+ if (instance_expr == null)
+ return null;
+ }
+
+ return this;
+ }
+
+ override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
+ {
+ if (!PropertyInfo.CanWrite){
+ Report.Error (154, loc,
+ "The property `" + PropertyInfo.Name +
+ "' can not be used in " +
+ "this context because it lacks a set accessor");
+ return null;
+ }
+
+ if (instance_expr != null) {
+ instance_expr = instance_expr.DoResolve (ec);
+ if (instance_expr == null)
+ return null;
+ }
return this;
}
override public void Emit (EmitContext ec)
{
- Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, Accessors [0], null);
+ MethodInfo method = Accessors [0];
+
+ //
+ // Special case: length of single dimension array is turned into ldlen
+ //
+ if ((method == TypeManager.system_int_array_get_length) ||
+ (method == TypeManager.int_array_get_length)){
+ Type iet = instance_expr.Type;
+
+ //
+ // System.Array.Length can be called, but the Type does not
+ // support invoking GetArrayRank, so test for that case first
+ //
+ if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)){
+ instance_expr.Emit (ec);
+ ec.ig.Emit (OpCodes.Ldlen);
+ return;
+ }
+ }
+
+ Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, method, null, loc);
}
ArrayList args = new ArrayList ();
args.Add (arg);
- Invocation.EmitCall (ec, false, IsStatic, instance_expr, Accessors [1], args);
+ Invocation.EmitCall (ec, false, IsStatic, instance_expr, Accessors [1], args, loc);
}
override public void EmitStatement (EmitContext ec)
/// <summary>
/// Fully resolved expression that evaluates to an Event
/// </summary>
- public class EventExpr : Expression {
+ public class EventExpr : Expression, IMemberExpr {
public readonly EventInfo EventInfo;
- Location loc;
- public Expression InstanceExpression;
-
- public readonly bool IsStatic;
+ public Expression instance_expr;
+ bool is_static;
MethodInfo add_accessor, remove_accessor;
public EventExpr (EventInfo ei, Location loc)
remove_accessor = TypeManager.GetRemoveMethod (ei);
if (add_accessor.IsStatic || remove_accessor.IsStatic)
- IsStatic = true;
+ is_static = true;
if (EventInfo is MyEventBuilder)
type = ((MyEventBuilder) EventInfo).EventType;
type = EventInfo.EventHandlerType;
}
- override public Expression DoResolve (EmitContext ec)
+ public string Name {
+ get {
+ return EventInfo.Name;
+ }
+ }
+
+ public bool IsInstance {
+ get {
+ return !is_static;
+ }
+ }
+
+ public bool IsStatic {
+ get {
+ return is_static;
+ }
+ }
+
+ public Type DeclaringType {
+ get {
+ return EventInfo.DeclaringType;
+ }
+ }
+
+ public Expression InstanceExpression {
+ get {
+ return instance_expr;
+ }
+
+ set {
+ instance_expr = value;
+ }
+ }
+
+ public override Expression DoResolve (EmitContext ec)
{
- // We are born fully resolved
+ if (instance_expr != null) {
+ instance_expr = instance_expr.DoResolve (ec);
+ if (instance_expr == null)
+ return null;
+ }
+
return this;
}
- override public void Emit (EmitContext ec)
+ public override void Emit (EmitContext ec)
{
- throw new Exception ("Should not happen I think");
+ Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
}
public void EmitAddOrRemove (EmitContext ec, Expression source)
if (((Binary) source).Oper == Binary.Operator.Addition)
Invocation.EmitCall (
- ec, false, IsStatic, InstanceExpression, add_accessor, args);
+ ec, false, IsStatic, instance_expr, add_accessor, args, loc);
else
Invocation.EmitCall (
- ec, false, IsStatic, InstanceExpression, remove_accessor, args);
+ ec, false, IsStatic, instance_expr, remove_accessor, args, loc);
}
}
}