DisableFlowAnalysis = 8,
// Set if this is resolving the first part of a MemberAccess.
- Intermediate = 16
+ Intermediate = 16,
+
+ // Disable control flow analysis _of struct_ while resolving the expression.
+ // This is used when resolving the instance expression of a field expression.
+ DisableStructFlowAnalysis = 32,
+
}
//
void AddressOf (EmitContext ec, AddressOp mode);
}
- /// <summary>
- /// We are either a namespace or a type.
- /// If we're a type, `IsType' is true and we may use `Type' to get
- /// a TypeExpr representing that type.
- /// </summary>
- public interface IAlias {
- bool IsType {
- get;
- }
-
- string Name {
- get;
- }
-
- TypeExpr ResolveAsType (EmitContext ec);
- }
-
/// <summary>
/// This interface is implemented by variables
/// </summary>
get;
}
- bool VerifyFixed (bool is_expression);
- }
-
- /// <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;
- }
+ bool VerifyFixed ();
}
/// <remarks>
protected Location loc;
public Type Type {
- get {
- return type;
- }
-
- set {
- type = value;
- }
+ get { return type; }
+ set { type = value; }
}
public Location Location {
- get {
- return loc;
- }
+ get { return loc; }
}
/// <summary>
/// </summary>
public void Error (int error, string s)
{
- if (!Location.IsNull (loc))
- Report.Error (error, loc, s);
- else
+ if (loc.IsNull)
Report.Error (error, s);
+ else
+ Report.Error (error, loc, s);
}
/// <summary>
AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
}
+ public virtual string GetSignatureForError ()
+ {
+ return TypeManager.CSharpName (type);
+ }
+
public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
{
MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
//
// If only accessible to the current class or children
//
- if (ma == MethodAttributes.Private) {
- Type declaring_type = mi.DeclaringType;
-
- if (invocation_type != declaring_type)
- return TypeManager.IsNestedChildOf (invocation_type, declaring_type);
-
- return true;
- }
- //
- // FamAndAssem requires that we not only derivate, but we are on the
- // same assembly.
- //
- if (ma == MethodAttributes.FamANDAssem){
- return (mi.DeclaringType.Assembly != invocation_type.Assembly);
- }
+ if (ma == MethodAttributes.Private)
+ return TypeManager.IsPrivateAccessible (invocation_type, mi.DeclaringType) ||
+ TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType);
- // Assembly and FamORAssem succeed if we're in the same assembly.
- if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
- if (mi.DeclaringType.Assembly == invocation_type.Assembly)
+ if (mi.DeclaringType.Assembly == invocation_type.Assembly) {
+ if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
return true;
+ } else {
+ if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
+ return false;
}
- // We already know that we aren't in the same assembly.
- if (ma == MethodAttributes.Assembly)
- return false;
-
// Family and FamANDAssem require that we derive.
- if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
+ // FamORAssem requires that we derive if in different assemblies.
+ if (ma == MethodAttributes.Family ||
+ ma == MethodAttributes.FamANDAssem ||
+ ma == MethodAttributes.FamORAssem) {
if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
return false;
public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
- return DoResolve (ec);
+ return null;
}
//
// This is used if the expression should be resolved as a type or namespace name.
// the default implementation fails.
//
- public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec)
+ public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
+ {
+ return ResolveAsTypeStep (ec, false);
+ }
+
+ public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
{
return null;
}
// value will be returned if the expression is not a type
// reference
//
- public virtual TypeExpr ResolveAsTypeTerminal (EmitContext ec)
+ public TypeExpr ResolveAsTypeTerminal (EmitContext ec)
+ {
+ return ResolveAsTypeTerminal (ec, false);
+ }
+
+ public virtual TypeExpr ResolveAsTypeTerminal (EmitContext ec, bool silent)
{
int errors = Report.Errors;
- FullNamedExpression fne = ResolveAsTypeStep (ec);
+ FullNamedExpression fne = ResolveAsTypeStep (ec, silent);
- if (fne == null) {
- if (errors == Report.Errors)
- Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
+ if (fne == null)
return null;
- }
if (fne.eclass != ExprClass.Type) {
- if (errors == Report.Errors)
- Report.Error (118, Location, "'{0}' denotes a '{1}', where a type was expected",
- fne.FullName, fne.ExprClassName ());
+ if (!silent && (errors == Report.Errors))
+ fne.Error_UnexpectedKind (null, "type", loc);
return null;
}
TypeExpr te = fne as TypeExpr;
if (!te.CheckAccessLevel (ec.DeclSpace)) {
- Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
+ ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type));
return null;
}
+ ConstructedType ct = te as ConstructedType;
+ if ((ct != null) && !ec.ResolvingTypeTree && !ct.CheckConstraints (ec))
+ return null;
+
return te;
}
+
+ public static void ErrorIsInaccesible (Location loc, string name)
+ {
+ Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", name);
+ }
+
+ public virtual void Error_ValueCannotBeConverted (Location loc, Type t)
+ {
+ Convert.Error_CannotImplicitConversion (loc, Type, t);
+ }
+
+ protected static void Error_TypeDoesNotContainDefinition (Location loc, Type type, string name)
+ {
+ Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'",
+ TypeManager.CSharpName (type), name);
+ }
+
+ ResolveFlags ExprClassToResolveFlags ()
+ {
+ switch (eclass) {
+ case ExprClass.Type:
+ case ExprClass.Namespace:
+ return ResolveFlags.Type;
+
+ case ExprClass.MethodGroup:
+ return ResolveFlags.MethodGroup;
+
+ case ExprClass.Value:
+ case ExprClass.Variable:
+ case ExprClass.PropertyAccess:
+ case ExprClass.EventAccess:
+ case ExprClass.IndexerAccess:
+ return ResolveFlags.VariableOrValue;
+
+ default:
+ throw new Exception ("Expression " + GetType () +
+ " ExprClass is Invalid after resolve");
+ }
+
+ }
/// <summary>
/// Resolves an expression and performs semantic analysis on it.
public Expression Resolve (EmitContext ec, ResolveFlags flags)
{
if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
- return ResolveAsTypeStep (ec);
+ return ResolveAsTypeStep (ec, false);
bool old_do_flow_analysis = ec.DoFlowAnalysis;
+ bool old_omit_struct_analysis = ec.OmitStructFlowAnalysis;
if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
ec.DoFlowAnalysis = false;
+ if ((flags & ResolveFlags.DisableStructFlowAnalysis) != 0)
+ ec.OmitStructFlowAnalysis = true;
Expression e;
bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
if (this is SimpleName)
- e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
+ e = ((SimpleName) this).DoResolve (ec, intermediate);
else
e = DoResolve (ec);
ec.DoFlowAnalysis = old_do_flow_analysis;
+ ec.OmitStructFlowAnalysis = old_omit_struct_analysis;
if (e == null)
return null;
- if ((e is TypeExpr) || (e is ComposedCast) || (e is Namespace)) {
- if ((flags & ResolveFlags.Type) == 0) {
- e.Error_UnexpectedKind (flags, loc);
- return null;
- }
-
- return e;
- }
-
- switch (e.eclass) {
- case ExprClass.Type:
- case ExprClass.Namespace:
- if ((flags & ResolveFlags.VariableOrValue) == 0) {
- e.Error_UnexpectedKind (flags, loc);
- return null;
- }
- break;
-
- case ExprClass.MethodGroup:
- if (RootContext.Version == LanguageVersion.ISO_1){
- 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) {
- Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
- Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
- FieldInfo fi = ((FieldExpr) e).FieldInfo;
-
- Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
- e.Error_UnexpectedKind (flags, loc);
- return null;
- }
- break;
-
- default:
- throw new Exception ("Expression " + e.GetType () +
- " ExprClass is Invalid after resolve");
+ if ((flags & e.ExprClassToResolveFlags ()) == 0) {
+ e.Error_UnexpectedKind (flags, loc);
+ return null;
}
if (e.type == null && !(e is Namespace)) {
/// </summary>
public Expression Resolve (EmitContext ec)
{
- return Resolve (ec, ResolveFlags.VariableOrValue);
+ Expression e = Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
+
+ if (e != null && e.eclass == ExprClass.MethodGroup && RootContext.Version == LanguageVersion.ISO_1) {
+ ((MethodGroupExpr) e).ReportUsageError ();
+ return null;
+ }
+ return e;
+ }
+
+ public Constant ResolveAsConstant (EmitContext ec, MemberCore mc)
+ {
+ Expression e = Resolve (ec);
+ if (e != null) {
+ Constant c = e as Constant;
+ if (c != null)
+ return c;
+
+ EmptyCast empty = e as EmptyCast;
+ if (empty != null) {
+ c = empty.Child as Constant;
+ if (c != null) {
+ // TODO: not sure about this maybe there is easier way how to use EmptyCast
+ if (e.Type.IsEnum)
+ c.Type = e.Type;
+
+ return c;
+ }
+ }
+ }
+
+ Const.Error_ExpressionMustBeConstant (loc, mc.GetSignatureForError ());
+ return null;
}
/// <summary>
/// Currently ResolveLValue wraps DoResolveLValue to perform sanity
/// checking and assertion checking on what we expect from Resolve
/// </remarks>
- public Expression ResolveLValue (EmitContext ec, Expression right_side)
+ public Expression ResolveLValue (EmitContext ec, Expression right_side, Location loc)
{
+ int errors = Report.Errors;
Expression e = DoResolveLValue (ec, right_side);
- if (e != null){
- if (e is SimpleName){
- SimpleName s = (SimpleName) e;
- MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
- ec.DeclSpace.Name, loc);
- return null;
- }
+ if (e == null) {
+ if (errors == Report.Errors)
+ Report.Error (131, loc, "The left-hand side of an assignment or mutating operation must be a variable, property or indexer");
+ return null;
+ }
+ if (e != null){
if (e.eclass == ExprClass.Invalid)
throw new Exception ("Expression " + e +
" ExprClass is Invalid after resolve");
/// <summary>
/// Returns a fully formed expression after a MemberLookup
/// </summary>
+ ///
+ // TODO: This can be heavily cached
public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
{
if (mi is EventInfo)
almostMatchedMembers.Clear ();
MemberInfo [] mi = TypeManager.MemberLookup (
- container_type, qualifier_type,queried_type, mt, bf, name,
+ container_type, qualifier_type, queried_type, mt, bf, name,
almostMatchedMembers);
if (mi == null)
public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
Type queried_type, string name, Location loc)
{
- return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
- name, AllMemberTypes, AllBindingFlags, loc);
+ if (ec.ResolvingTypeTree)
+ return MemberLookup (ec, ec.ContainerType, qualifier_type,
+ queried_type, name, MemberTypes.NestedType,
+ AllBindingFlags, loc);
+ else
+ return MemberLookup (ec, ec.ContainerType, qualifier_type,
+ queried_type, name, AllMemberTypes,
+ AllBindingFlags, loc);
}
public static Expression MethodLookup (EmitContext ec, Type queried_type,
if (e == null && errors == Report.Errors)
// No errors were reported by MemberLookup, but there was an error.
- MemberLookupFailed (ec, qualifier_type, queried_type, name,
- null, loc);
+ MemberLookupFailed (ec, qualifier_type, queried_type, name, null, true, loc);
return e;
}
public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
Type queried_type, string name,
- string class_name, Location loc)
+ string class_name, bool complain_if_none_found,
+ Location loc)
{
if (almostMatchedMembers.Count != 0) {
- if (qualifier_type == null) {
- foreach (MemberInfo m in almostMatchedMembers)
- Report.Error (38, loc,
- "Cannot access non-static member `{0}' via nested type `{1}'",
- TypeManager.GetFullNameSignature (m),
- TypeManager.CSharpName (ec.ContainerType));
- return;
- }
-
-
- if (qualifier_type != ec.ContainerType) {
- // Although a derived class can access protected members of
- // its base class it cannot do so through an instance of the
- // base class (CS1540). If the qualifier_type is a base of the
- // ec.ContainerType and the lookup succeeds with the latter one,
- // then we are in this situation.
- for (int i = 0; i < almostMatchedMembers.Count; ++i) {
- MemberInfo m = (MemberInfo) almostMatchedMembers [i];
- for (int j = 0; j < i; ++j) {
- if (m == almostMatchedMembers [j]) {
- m = null;
- break;
- }
+ for (int i = 0; i < almostMatchedMembers.Count; ++i) {
+ MemberInfo m = (MemberInfo) almostMatchedMembers [i];
+ for (int j = 0; j < i; ++j) {
+ if (m == almostMatchedMembers [j]) {
+ m = null;
+ break;
}
- if (m == null)
- continue;
-
- Report.SymbolRelatedToPreviousError (m);
+ }
+ if (m == null)
+ continue;
+
+ Type declaring_type = m.DeclaringType;
+
+ Report.SymbolRelatedToPreviousError (m);
+ if (qualifier_type == null) {
+ Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
+ TypeManager.CSharpName (m.DeclaringType),
+ TypeManager.CSharpName (ec.ContainerType));
+ } else if (qualifier_type != ec.ContainerType &&
+ TypeManager.IsNestedFamilyAccessible (ec.ContainerType, declaring_type)) {
+ // Although a derived class can access protected members of
+ // its base class it cannot do so through an instance of the
+ // base class (CS1540). If the qualifier_type is a base of the
+ // ec.ContainerType and the lookup succeeds with the latter one,
+ // then we are in this situation.
Report.Error (1540, loc,
"Cannot access protected member `{0}' via a qualifier of type `{1}';"
+ " the qualifier must be of type `{2}' (or derived from it)",
TypeManager.GetFullNameSignature (m),
TypeManager.CSharpName (qualifier_type),
TypeManager.CSharpName (ec.ContainerType));
+ } else {
+ ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (m));
}
- return;
}
almostMatchedMembers.Clear ();
+ return;
}
- MemberInfo[] mi = TypeManager.MemberLookup (queried_type, null, queried_type,
- AllMemberTypes, AllBindingFlags |
- BindingFlags.NonPublic, name, null);
+ MemberInfo[] lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
+ AllMemberTypes, AllBindingFlags |
+ BindingFlags.NonPublic, name, null);
+
+ if (lookup == null) {
+ if (!complain_if_none_found)
+ return;
- if (mi == null) {
if (class_name != null)
- Report.Error (103, loc, "The name `" + name + "' could not be " +
- "found in `" + class_name + "'");
+ Report.Error (103, loc, "The name `{0}' does not exist in the context of `{1}'",
+ name, class_name);
else
- Report.Error (
- 117, loc, "`" + queried_type + "' does not contain a " +
- "definition for `" + name + "'");
+ Error_TypeDoesNotContainDefinition (loc, queried_type, name);
return;
}
if (TypeManager.MemberLookup (queried_type, null, queried_type,
AllMemberTypes, AllBindingFlags |
BindingFlags.NonPublic, name, null) == null) {
- if ((mi.Length == 1) && (mi [0] is Type)) {
- Type t = (Type) mi [0];
+ if ((lookup.Length == 1) && (lookup [0] is Type)) {
+ Type t = (Type) lookup [0];
Report.Error (305, loc,
"Using the generic type `{0}' " +
}
}
- if (name == ".ctor" && TypeManager.FindMembers (qualifier_type, MemberTypes.Constructor,
- BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null).Count == 0)
+ MemberList ml = TypeManager.FindMembers (queried_type, MemberTypes.Constructor,
+ BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null);
+ if (name == ".ctor" && ml.Count == 0)
{
- Report.Error (143, loc, String.Format ("The type '{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
+ Report.Error (143, loc, String.Format ("The type `{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
return;
}
- if (qualifier_type != null) {
- Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
- } else {
- Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
+ ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (lookup [0]));
}
- }
-
- static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
- {
- EventInfo ei = event_expr.EventInfo;
- return TypeManager.GetPrivateFieldOfEvent (ei);
- }
-
/// <summary>
/// Returns an expression that can be used to invoke operator true
/// on the expression if it exists.
if (e.Type == TypeManager.bool_type)
return e;
- Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
+ Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
if (converted != null)
return converted;
return operator_true;
}
- public string ExprClassName ()
+ string ExprClassName ()
{
switch (eclass){
case ExprClass.Invalid:
/// <summary>
/// Reports that we were expecting `expr' to be of class `expected'
/// </summary>
- public void Error_UnexpectedKind (string expected, Location loc)
+ public void Error_UnexpectedKind (EmitContext ec, string expected, Location loc)
+ {
+ Error_UnexpectedKind (ec, expected, ExprClassName (), loc);
+ }
+
+ public void Error_UnexpectedKind (EmitContext ec, string expected, string was, Location loc)
{
- Report.Error (118, loc, "Expression denotes a `" + ExprClassName () +
- "' where a `" + expected + "' was expected");
+ string name = GetSignatureForError ();
+ if (ec != null)
+ name = ec.DeclSpace.GetSignatureForError () + '.' + name;
+
+ Report.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected",
+ name, was, expected);
}
public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
{
- ArrayList valid = new ArrayList (10);
+ string [] valid = new string [4];
+ int count = 0;
if ((flags & ResolveFlags.VariableOrValue) != 0) {
- valid.Add ("variable");
- valid.Add ("value");
+ valid [count++] = "variable";
+ valid [count++] = "value";
}
if ((flags & ResolveFlags.Type) != 0)
- valid.Add ("type");
+ valid [count++] = "type";
if ((flags & ResolveFlags.MethodGroup) != 0)
- valid.Add ("method group");
+ valid [count++] = "method group";
- if (valid.Count == 0)
- valid.Add ("unknown");
+ if (count == 0)
+ valid [count++] = "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 ");
+ StringBuilder sb = new StringBuilder (valid [0]);
+ for (int i = 1; i < count - 1; i++) {
+ sb.Append ("', `");
sb.Append (valid [i]);
}
+ if (count > 1) {
+ sb.Append ("' or `");
+ sb.Append (valid [count - 1]);
+ }
- Report.Error (119, loc, "Expression denotes a `" + ExprClassName () + "' where " +
- "a `" + sb.ToString () + "' was expected");
+ Report.Error (119, loc,
+ "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName (), sb);
}
- static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
- {
- Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
- TypeManager.CSharpName (t));
- }
-
public static void UnsafeError (Location loc)
{
- Report.Error (214, loc, "Pointers may only be used in an unsafe context");
- }
-
- /// <summary>
- /// Converts the IntConstant, UIntConstant, LongConstant or
- /// ULongConstant into the integral target_type. Notice
- /// that we do not return an `Expression' we do return
- /// a boxed integral type.
- ///
- /// FIXME: Since I added the new constants, we need to
- /// also support conversions from CharConstant, ByteConstant,
- /// SByteConstant, UShortConstant, ShortConstant
- ///
- /// This is used by the switch statement, so the domain
- /// of work is restricted to the literals above, and the
- /// targets are int32, uint32, char, byte, sbyte, ushort,
- /// short, uint64 and int64
- /// </summary>
- public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
- {
- if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
- Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
- return null;
- }
-
- string s = "";
-
- if (c.Type == target_type)
- return ((Constant) c).GetValue ();
-
- //
- // Make into one of the literals we handle, we dont really care
- // about this value as we will just return a few limited types
- //
- if (c is EnumConstant)
- c = ((EnumConstant)c).WidenToCompilerConstant ();
-
- if (c is IntConstant){
- int v = ((IntConstant) c).Value;
-
- if (target_type == TypeManager.uint32_type){
- if (v >= 0)
- return (uint) v;
- } else if (target_type == TypeManager.char_type){
- if (v >= Char.MinValue && v <= Char.MaxValue)
- return (char) v;
- } else if (target_type == TypeManager.byte_type){
- if (v >= Byte.MinValue && v <= Byte.MaxValue)
- return (byte) v;
- } else if (target_type == TypeManager.sbyte_type){
- if (v >= SByte.MinValue && v <= SByte.MaxValue)
- return (sbyte) v;
- } else if (target_type == TypeManager.short_type){
- if (v >= Int16.MinValue && v <= UInt16.MaxValue)
- return (short) v;
- } else if (target_type == TypeManager.ushort_type){
- if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
- return (ushort) v;
- } else if (target_type == TypeManager.int64_type)
- return (long) v;
- else if (target_type == TypeManager.uint64_type){
- if (v > 0)
- return (ulong) v;
- }
-
- s = v.ToString ();
- } else if (c is UIntConstant){
- uint v = ((UIntConstant) c).Value;
-
- if (target_type == TypeManager.int32_type){
- if (v <= Int32.MaxValue)
- return (int) v;
- } else if (target_type == TypeManager.char_type){
- if (v >= Char.MinValue && v <= Char.MaxValue)
- return (char) v;
- } else if (target_type == TypeManager.byte_type){
- if (v <= Byte.MaxValue)
- return (byte) v;
- } else if (target_type == TypeManager.sbyte_type){
- if (v <= SByte.MaxValue)
- return (sbyte) v;
- } else if (target_type == TypeManager.short_type){
- if (v <= UInt16.MaxValue)
- return (short) v;
- } else if (target_type == TypeManager.ushort_type){
- if (v <= UInt16.MaxValue)
- return (ushort) v;
- } else if (target_type == TypeManager.int64_type)
- return (long) v;
- else if (target_type == TypeManager.uint64_type)
- return (ulong) v;
- s = v.ToString ();
- } else if (c is LongConstant){
- long v = ((LongConstant) c).Value;
-
- if (target_type == TypeManager.int32_type){
- if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
- return (int) v;
- } else if (target_type == TypeManager.uint32_type){
- if (v >= 0 && v <= UInt32.MaxValue)
- return (uint) v;
- } else if (target_type == TypeManager.char_type){
- if (v >= Char.MinValue && v <= Char.MaxValue)
- return (char) v;
- } else if (target_type == TypeManager.byte_type){
- if (v >= Byte.MinValue && v <= Byte.MaxValue)
- return (byte) v;
- } else if (target_type == TypeManager.sbyte_type){
- if (v >= SByte.MinValue && v <= SByte.MaxValue)
- return (sbyte) v;
- } else if (target_type == TypeManager.short_type){
- if (v >= Int16.MinValue && v <= UInt16.MaxValue)
- return (short) v;
- } else if (target_type == TypeManager.ushort_type){
- if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
- return (ushort) v;
- } else if (target_type == TypeManager.uint64_type){
- if (v > 0)
- return (ulong) v;
- }
- s = v.ToString ();
- } else if (c is ULongConstant){
- ulong v = ((ULongConstant) c).Value;
-
- if (target_type == TypeManager.int32_type){
- if (v <= Int32.MaxValue)
- return (int) v;
- } else if (target_type == TypeManager.uint32_type){
- if (v <= UInt32.MaxValue)
- return (uint) v;
- } else if (target_type == TypeManager.char_type){
- if (v >= Char.MinValue && v <= Char.MaxValue)
- return (char) v;
- } else if (target_type == TypeManager.byte_type){
- if (v >= Byte.MinValue && v <= Byte.MaxValue)
- return (byte) v;
- } else if (target_type == TypeManager.sbyte_type){
- if (v <= (int) SByte.MaxValue)
- return (sbyte) v;
- } else if (target_type == TypeManager.short_type){
- if (v <= UInt16.MaxValue)
- return (short) v;
- } else if (target_type == TypeManager.ushort_type){
- if (v <= UInt16.MaxValue)
- return (ushort) v;
- } else if (target_type == TypeManager.int64_type){
- if (v <= Int64.MaxValue)
- return (long) v;
- }
- s = v.ToString ();
- } else if (c is ByteConstant){
- byte v = ((ByteConstant) c).Value;
-
- if (target_type == TypeManager.int32_type)
- return (int) v;
- else if (target_type == TypeManager.uint32_type)
- return (uint) v;
- else if (target_type == TypeManager.char_type)
- return (char) v;
- else if (target_type == TypeManager.sbyte_type){
- if (v <= SByte.MaxValue)
- return (sbyte) v;
- } else if (target_type == TypeManager.short_type)
- return (short) v;
- else if (target_type == TypeManager.ushort_type)
- return (ushort) v;
- else if (target_type == TypeManager.int64_type)
- return (long) v;
- else if (target_type == TypeManager.uint64_type)
- return (ulong) v;
- s = v.ToString ();
- } else if (c is SByteConstant){
- sbyte v = ((SByteConstant) c).Value;
-
- if (target_type == TypeManager.int32_type)
- return (int) v;
- else if (target_type == TypeManager.uint32_type){
- if (v >= 0)
- return (uint) v;
- } else if (target_type == TypeManager.char_type){
- if (v >= 0)
- return (char) v;
- } else if (target_type == TypeManager.byte_type){
- if (v >= 0)
- return (byte) v;
- } else if (target_type == TypeManager.short_type)
- return (short) v;
- else if (target_type == TypeManager.ushort_type){
- if (v >= 0)
- return (ushort) v;
- } else if (target_type == TypeManager.int64_type)
- return (long) v;
- else if (target_type == TypeManager.uint64_type){
- if (v >= 0)
- return (ulong) v;
- }
- s = v.ToString ();
- } else if (c is ShortConstant){
- short v = ((ShortConstant) c).Value;
-
- if (target_type == TypeManager.int32_type){
- return (int) v;
- } else if (target_type == TypeManager.uint32_type){
- if (v >= 0)
- return (uint) v;
- } else if (target_type == TypeManager.char_type){
- if (v >= 0)
- return (char) v;
- } else if (target_type == TypeManager.byte_type){
- if (v >= Byte.MinValue && v <= Byte.MaxValue)
- return (byte) v;
- } else if (target_type == TypeManager.sbyte_type){
- if (v >= SByte.MinValue && v <= SByte.MaxValue)
- return (sbyte) v;
- } else if (target_type == TypeManager.ushort_type){
- if (v >= 0)
- return (ushort) v;
- } else if (target_type == TypeManager.int64_type)
- return (long) v;
- else if (target_type == TypeManager.uint64_type)
- return (ulong) v;
-
- s = v.ToString ();
- } else if (c is UShortConstant){
- ushort v = ((UShortConstant) c).Value;
-
- if (target_type == TypeManager.int32_type)
- return (int) v;
- else if (target_type == TypeManager.uint32_type)
- return (uint) v;
- else if (target_type == TypeManager.char_type){
- if (v >= Char.MinValue && v <= Char.MaxValue)
- return (char) v;
- } else if (target_type == TypeManager.byte_type){
- if (v >= Byte.MinValue && v <= Byte.MaxValue)
- return (byte) v;
- } else if (target_type == TypeManager.sbyte_type){
- if (v <= SByte.MaxValue)
- return (byte) v;
- } else if (target_type == TypeManager.short_type){
- if (v <= Int16.MaxValue)
- return (short) v;
- } else if (target_type == TypeManager.int64_type)
- return (long) v;
- else if (target_type == TypeManager.uint64_type)
- return (ulong) v;
-
- s = v.ToString ();
- } else if (c is CharConstant){
- char v = ((CharConstant) c).Value;
-
- if (target_type == TypeManager.int32_type)
- return (int) v;
- else if (target_type == TypeManager.uint32_type)
- return (uint) v;
- else if (target_type == TypeManager.byte_type){
- if (v >= Byte.MinValue && v <= Byte.MaxValue)
- return (byte) v;
- } else if (target_type == TypeManager.sbyte_type){
- if (v <= SByte.MaxValue)
- return (sbyte) v;
- } else if (target_type == TypeManager.short_type){
- if (v <= Int16.MaxValue)
- return (short) v;
- } else if (target_type == TypeManager.ushort_type)
- return (short) v;
- else if (target_type == TypeManager.int64_type)
- return (long) v;
- else if (target_type == TypeManager.uint64_type)
- return (ulong) v;
-
- s = v.ToString ();
- }
- Error_ConstantValueCannotBeConverted (loc, s, target_type);
- return null;
+ Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
}
//
{
Report.Error (248, loc, "Cannot create an array with a negative size");
}
+
+ protected void Error_CannotCallAbstractBase (string name)
+ {
+ Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
+ }
//
// Converts `source' to an int, uint, long or ulong.
public EmptyCast (Expression child, Type return_type)
{
eclass = child.eclass;
+ loc = child.Location;
type = return_type;
this.child = child;
}
child.Emit (ec);
}
}
+ /// <summary>
+ /// This is a numeric cast to a Decimal
+ /// </summary>
+ public class CastToDecimal : EmptyCast {
- //
- // We need to special case this since an empty cast of
- // a NullLiteral is still a Constant
- //
- public class NullCast : Constant {
- protected Expression child;
-
- public NullCast (Expression child, Type return_type)
- {
- eclass = child.eclass;
- type = return_type;
- this.child = child;
- }
+ MethodInfo conversion_operator;
- override public string AsString ()
+ public CastToDecimal (EmitContext ec, Expression child)
+ : this (ec, child, false)
{
- return "null";
}
- public override object GetValue ()
+ public CastToDecimal (EmitContext ec, Expression child, bool find_explicit)
+ : base (child, TypeManager.decimal_type)
{
- return null;
+ conversion_operator = GetConversionOperator (ec, find_explicit);
+
+ if (conversion_operator == null)
+ Convert.Error_CannotImplicitConversion (loc, child.Type, type);
}
- public override Expression DoResolve (EmitContext ec)
+ // Returns the implicit operator that converts from
+ // 'child.Type' to System.Decimal.
+ MethodInfo GetConversionOperator (EmitContext ec, bool find_explicit)
{
- // This should never be invoked, we are born in fully
- // initialized state.
+ string operator_name = "op_Implicit";
- return this;
- }
+ if (find_explicit)
+ operator_name = "op_Explicit";
+
+ MethodGroupExpr opers = Expression.MethodLookup (
+ ec, type, operator_name, loc) as MethodGroupExpr;
+ if (opers == null)
+ Convert.Error_CannotImplicitConversion (loc, child.Type, type);
+
+ foreach (MethodInfo oper in opers.Methods) {
+ ParameterData pd = TypeManager.GetParameterData (oper);
+
+ if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
+ return oper;
+ }
+
+ return null;
+ }
public override void Emit (EmitContext ec)
{
+ ILGenerator ig = ec.ig;
child.Emit (ec);
- }
+
+ ig.Emit (OpCodes.Call, conversion_operator);
+ }
+ }
+ /// <summary>
+ /// This is an explicit numeric cast from a Decimal
+ /// </summary>
+ public class CastFromDecimal : EmptyCast
+ {
+ MethodInfo conversion_operator;
+ public CastFromDecimal (EmitContext ec, Expression child, Type return_type)
+ : base (child, return_type)
+ {
+ if (child.Type != TypeManager.decimal_type)
+ throw new InternalErrorException (
+ "The expected type is Decimal, instead it is " + child.Type.FullName);
+
+ conversion_operator = GetConversionOperator (ec);
+ if (conversion_operator == null)
+ Convert.Error_CannotImplicitConversion (loc, child.Type, type);
+ }
+
+ // Returns the explicit operator that converts from an
+ // express of type System.Decimal to 'type'.
+ MethodInfo GetConversionOperator (EmitContext ec)
+ {
+ MethodGroupExpr opers = Expression.MethodLookup (
+ ec, child.Type, "op_Explicit", loc) as MethodGroupExpr;
+
+ if (opers == null)
+ Convert.Error_CannotImplicitConversion (loc, child.Type, type);
+
+ foreach (MethodInfo oper in opers.Methods) {
+ ParameterData pd = TypeManager.GetParameterData (oper);
+
+ if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
+ return oper;
+ }
+
+ return null;
+ }
+ public override void Emit (EmitContext ec)
+ {
+ ILGenerator ig = ec.ig;
+ child.Emit (ec);
+
+ ig.Emit (OpCodes.Call, conversion_operator);
+ }
+ }
+
+ //
+ // We need to special case this since an empty cast of
+ // a NullLiteral is still a Constant
+ //
+ public class NullCast : Constant {
+ protected Expression child;
+
+ public NullCast (Expression child, Type return_type)
+ {
+ eclass = child.eclass;
+ type = return_type;
+ this.child = child;
+ }
+
+ override public string AsString ()
+ {
+ return "null";
+ }
+
+ public override object GetValue ()
+ {
+ return null;
+ }
+
+ public override Expression DoResolve (EmitContext ec)
+ {
+ // This should never be invoked, we are born in fully
+ // initialized state.
+
+ return this;
+ }
+
+ public override void Emit (EmitContext ec)
+ {
+ child.Emit (ec);
+ }
+
+ public override Constant Increment ()
+ {
+ throw new NotSupportedException ();
+ }
+
+ public override bool IsDefaultValue {
+ get {
+ throw new NotImplementedException ();
+ }
+ }
public override bool IsNegative {
get {
return Child.GetValue ();
}
- public object GetValueAsEnumType ()
+ public override object GetTypedValue ()
{
+ // FIXME: runtime is not ready to work with just emited enums
+ if (!RootContext.StdLib) {
+ return Child.GetValue ();
+ }
+
return System.Enum.ToObject (type, Child.GetValue ());
}
-
- //
- // Converts from one of the valid underlying types for an enumeration
- // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
- // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
- //
- public Constant WidenToCompilerConstant ()
+
+ public override void Error_ValueCannotBeConverted (Location loc, Type t)
{
- Type t = TypeManager.EnumToUnderlying (Child.Type);
- object v = ((Constant) Child).GetValue ();;
-
- if (t == TypeManager.int32_type)
- return new IntConstant ((int) v);
- if (t == TypeManager.uint32_type)
- return new UIntConstant ((uint) v);
- if (t == TypeManager.int64_type)
- return new LongConstant ((long) v);
- if (t == TypeManager.uint64_type)
- return new ULongConstant ((ulong) v);
- if (t == TypeManager.short_type)
- return new ShortConstant ((short) v);
- if (t == TypeManager.ushort_type)
- return new UShortConstant ((ushort) v);
- if (t == TypeManager.byte_type)
- return new ByteConstant ((byte) v);
- if (t == TypeManager.sbyte_type)
- return new SByteConstant ((sbyte) v);
-
- throw new Exception ("Invalid enumeration underlying type: " + t);
+ Convert.Error_CannotImplicitConversion (loc, Type, t);
}
- //
- // Extracts the value in the enumeration on its native representation
- //
- public object GetPlainValue ()
- {
- Type t = TypeManager.EnumToUnderlying (Child.Type);
- object v = ((Constant) Child).GetValue ();;
-
- if (t == TypeManager.int32_type)
- return (int) v;
- if (t == TypeManager.uint32_type)
- return (uint) v;
- if (t == TypeManager.int64_type)
- return (long) v;
- if (t == TypeManager.uint64_type)
- return (ulong) v;
- if (t == TypeManager.short_type)
- return (short) v;
- if (t == TypeManager.ushort_type)
- return (ushort) v;
- if (t == TypeManager.byte_type)
- return (byte) v;
- if (t == TypeManager.sbyte_type)
- return (sbyte) v;
-
- return null;
- }
-
public override string AsString ()
{
return Child.AsString ();
{
return Child.ConvertToInt ();
}
-
+
+ public override Constant Increment()
+ {
+ return new EnumConstant (Child.Increment (), type);
+ }
+
+ public override bool IsDefaultValue {
+ get {
+ return Child.IsDefaultValue;
+ }
+ }
+
public override bool IsZeroInteger {
get { return Child.IsZeroInteger; }
}
return Child.IsNegative;
}
}
+
+ public override Constant ToType (Type type, Location loc)
+ {
+ if (Type == type) {
+ // This is workaround of mono bug. It can be removed when the latest corlib spreads enough
+ if (TypeManager.IsEnumType (type.UnderlyingSystemType))
+ return this;
+
+ if (type.UnderlyingSystemType != Child.Type)
+ Child = Child.ToType (type.UnderlyingSystemType, loc);
+ return this;
+ }
+
+ if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, this, type)){
+ Error_ValueCannotBeConverted (loc, type);
+ return null;
+ }
+
+ return Child.ToType (type, loc);
+ }
+
}
/// <summary>
/// </summary>
public class BoxedCast : EmptyCast {
- public BoxedCast (Expression expr)
- : base (expr, TypeManager.object_type)
- {
- eclass = ExprClass.Value;
- }
-
public BoxedCast (Expression expr, Type target_type)
: base (expr, target_type)
{
public class SimpleName : Expression {
public string Name;
public readonly TypeArguments Arguments;
+ bool in_transit;
public SimpleName (string name, Location l)
{
loc = l;
}
- public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
+ public SimpleName (string name, TypeParameter[] type_params, Location l)
{
- 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+"'");
+ Name = name;
+ loc = l;
+
+ Arguments = new TypeArguments (l);
+ foreach (TypeParameter type_param in type_params)
+ Arguments.Add (new TypeParameterExpr (type_param, l));
}
-
- //
- // Checks whether we are trying to access an instance
- // property, method or field from a static body.
- //
- Expression MemberStaticCheck (EmitContext ec, Expression e)
+
+ public static string RemoveGenericArity (string name)
{
- if (e is IMemberExpr){
- IMemberExpr member = (IMemberExpr) e;
-
- if (!member.IsStatic){
- Error_ObjectRefRequired (ec, loc, Name);
- return null;
+ int start = 0;
+ StringBuilder sb = new StringBuilder ();
+ while (start < name.Length) {
+ int pos = name.IndexOf ('`', start);
+ if (pos < 0) {
+ sb.Append (name.Substring (start));
+ break;
}
+
+ sb.Append (name.Substring (start, pos-start));
+
+ pos++;
+ while ((pos < name.Length) && Char.IsNumber (name [pos]))
+ pos++;
+
+ start = pos;
}
- return e;
+ return sb.ToString ();
}
-
+
+ public SimpleName GetMethodGroup ()
+ {
+ return new SimpleName (RemoveGenericArity (Name), Arguments, loc);
+ }
+
+ public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
+ {
+ if (ec.IsFieldInitializer)
+ Report.Error (236, l,
+ "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
+ name);
+ else {
+ if (name.LastIndexOf ('.') > 0)
+ name = name.Substring (name.LastIndexOf ('.') + 1);
+
+ Report.Error (
+ 120, l, "`{0}': An object reference is required for the nonstatic field, method or property",
+ name);
+ }
+ }
+
+ public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
+ {
+ return resolved_to != null && resolved_to.Type != null &&
+ resolved_to.Type.Name == Name &&
+ (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
+ }
+
public override Expression DoResolve (EmitContext ec)
{
- return SimpleNameResolve (ec, null, false, false);
+ return SimpleNameResolve (ec, null, false);
}
public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
- return SimpleNameResolve (ec, right_side, false, false);
+ return SimpleNameResolve (ec, right_side, false);
}
- public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
+ public Expression DoResolve (EmitContext ec, bool intermediate)
{
- return SimpleNameResolve (ec, null, true, intermediate);
+ return SimpleNameResolve (ec, null, intermediate);
+ }
+
+ private bool IsNestedChild (Type t, Type parent)
+ {
+ if (parent == null)
+ return false;
+
+ while (parent != null) {
+ if (parent.IsGenericInstance)
+ parent = parent.GetGenericTypeDefinition ();
+
+ if (TypeManager.IsNestedChildOf (t, parent))
+ return true;
+
+ parent = parent.BaseType;
+ }
+
+ return false;
}
- public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
+ FullNamedExpression ResolveNested (EmitContext ec, Type t)
{
+ if (!t.IsGenericTypeDefinition)
+ return null;
+
DeclSpace ds = ec.DeclSpace;
- FullNamedExpression dt;
+ while (ds != null) {
+ if (IsNestedChild (t, ds.TypeBuilder))
+ break;
- dt = ds.LookupGeneric (Name, loc);
- if (dt != null)
- return dt.ResolveAsTypeStep (ec);
+ ds = ds.Parent;
+ }
- int errors = Report.Errors;
- dt = ec.ResolvingTypeTree
- ? ds.FindType (loc, Name)
- : ds.LookupType (Name, true, loc);
- if (Report.Errors != errors)
+ if (ds == null)
return null;
- return dt;
+ Type[] gen_params = t.GetGenericArguments ();
+
+ int arg_count = Arguments != null ? Arguments.Count : 0;
+
+ for (; (ds != null) && ds.IsGeneric; ds = ds.Parent) {
+ if (arg_count + ds.CountTypeParameters == gen_params.Length) {
+ TypeArguments new_args = new TypeArguments (loc);
+ foreach (TypeParameter param in ds.TypeParameters)
+ new_args.Add (new TypeParameterExpr (param, loc));
+
+ if (Arguments != null)
+ new_args.Add (Arguments);
+
+ return new ConstructedType (t, new_args, loc);
+ }
+ }
+
+ return null;
}
- Expression SimpleNameResolve (EmitContext ec, Expression right_side,
- bool allow_static, bool intermediate)
+ public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
{
- Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
- if (e == null)
- return null;
+ FullNamedExpression fne = ec.DeclSpace.LookupGeneric (Name, loc);
+ if (fne != null)
+ return fne.ResolveAsTypeStep (ec, silent);
- Block current_block = ec.CurrentBlock;
- if (current_block != null){
- if (current_block.IsVariableNameUsedInChildBlock (Name)) {
- Report.Error (135, Location,
- "'{0}' has a different meaning in a child block", Name);
- return null;
+ int errors = Report.Errors;
+ fne = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
+
+ if (fne != null) {
+ if (fne.Type == null)
+ return fne;
+
+ FullNamedExpression nested = ResolveNested (ec, fne.Type);
+ if (nested != null)
+ return nested.ResolveAsTypeStep (ec);
+
+ if (Arguments != null) {
+ ConstructedType ct = new ConstructedType (fne, Arguments, loc);
+ return ct.ResolveAsTypeStep (ec);
}
+
+ return fne;
}
- if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
- UnsafeError (loc);
+ if (silent || errors != Report.Errors)
return null;
+
+ MemberCore mc = ec.DeclSpace.GetDefinition (Name);
+ if (mc != null) {
+ Error_UnexpectedKind (ec, "type", GetMemberType (mc), loc);
+ } else {
+ NamespaceEntry.Error_NamespaceNotFound (loc, Name);
}
- return e;
+ return null;
+ }
+
+ // TODO: I am still not convinced about this. If someone else will need it
+ // implement this as virtual property in MemberCore hierarchy
+ string GetMemberType (MemberCore mc)
+ {
+ if (mc is PropertyBase)
+ return "property";
+ if (mc is Indexer)
+ return "indexer";
+ if (mc is FieldBase)
+ return "field";
+
+ return "type";
+ }
+
+ Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
+ {
+ if (in_transit)
+ return null;
+ in_transit = true;
+
+ Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
+ if (e == null)
+ return null;
+
+ if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
+ return e;
+
+ return null;
}
/// <remarks>
/// Local Variables and Parameters are handled at
/// parse time, so they never occur as SimpleNames.
///
- /// The `allow_static' flag is used by MemberAccess only
+ /// The `intermediate' flag is used by MemberAccess only
/// and it is used to inform us that it is ok for us to
/// avoid the static check, because MemberAccess might end
/// up resolving the Name as a Type name and the access as
/// Type is both an instance variable and a Type; Type.GetType
/// is the static method not an instance method of type.
/// </remarks>
- Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
+ Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
{
Expression e = null;
if (current_block != null){
LocalInfo vi = current_block.GetLocalInfo (Name);
if (vi != null){
- Expression var;
-
- var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
-
- if (right_side != null)
- return var.ResolveLValue (ec, right_side);
- else
- return var.Resolve (ec);
+ LocalVariableReference var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
+ if (right_side != null) {
+ return var.ResolveLValue (ec, right_side, loc);
+ } else {
+ ResolveFlags rf = ResolveFlags.VariableOrValue;
+ if (intermediate)
+ rf |= ResolveFlags.DisableFlowAnalysis;
+ return var.Resolve (ec, rf);
+ }
}
- ParameterReference pref = current_block.GetParameterReference (Name, loc);
+ ParameterReference pref = current_block.Toplevel.GetParameterReference (Name, loc);
if (pref != null) {
if (right_side != null)
- return pref.ResolveLValue (ec, right_side);
+ return pref.ResolveLValue (ec, right_side, loc);
else
return pref.Resolve (ec);
}
almost_matched_type = ec.ContainerType;
almost_matched = (ArrayList) almostMatchedMembers.Clone ();
}
- e = ResolveAsTypeStep (ec);
+ e = ResolveAsTypeStep (ec, false);
}
if (e == null) {
almostMatchedMembers = almost_matched;
if (almost_matched_type == null)
almost_matched_type = ec.ContainerType;
- MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, loc);
+ MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
return null;
}
if (e is TypeExpr)
return e;
- if (e is IMemberExpr) {
- e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
+ if (e is MemberExpr) {
+ MemberExpr me = (MemberExpr) e;
+
+ Expression left;
+ if (me.IsInstance) {
+ if (ec.IsStatic || ec.IsFieldInitializer) {
+ //
+ // Note that an MemberExpr can be both IsInstance and IsStatic.
+ // An unresolved MethodGroupExpr can contain both kinds of methods
+ // and each predicate is true if the MethodGroupExpr contains
+ // at least one of that kind of method.
+ //
+
+ if (!me.IsStatic &&
+ (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
+ Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
+ return null;
+ }
+
+ //
+ // Pass the buck to MemberAccess and Invocation.
+ //
+ left = EmptyExpression.Null;
+ } else {
+ left = ec.GetThis (loc);
+ }
+ } else {
+ left = new TypeExpression (ec.ContainerType, loc);
+ }
+
+ e = me.ResolveMemberAccess (ec, left, loc, null);
if (e == null)
return null;
- IMemberExpr me = e as IMemberExpr;
+ me = e as MemberExpr;
if (me == null)
return e;
return mg.ResolveGeneric (ec, Arguments);
}
- // 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 (!me.IsStatic &&
TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
me.InstanceExpression.Type != me.DeclaringType &&
!TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
- (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
- Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
- "outer type `" + me.DeclaringType + "' via nested type `" +
- me.InstanceExpression.Type + "'");
+ (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
+ Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
+ TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
return null;
}
return (right_side != null)
- ? e.DoResolveLValue (ec, right_side)
- : e.DoResolve (ec);
+ ? me.DoResolveLValue (ec, right_side)
+ : me.DoResolve (ec);
}
- if (ec.IsStatic || ec.IsFieldInitializer){
- if (allow_static)
- return e;
-
- return MemberStaticCheck (ec, e);
- } else
- return e;
+ return e;
}
public override void Emit (EmitContext ec)
{
return Name;
}
+
+ public override string GetSignatureForError ()
+ {
+ return Name;
+ }
}
/// <summary>
/// section 10.8.1 (Fully Qualified Names).
/// </summary>
public abstract class FullNamedExpression : Expression {
- public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
+ public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
{
return this;
}
/// Fully resolved expression that evaluates to a type
/// </summary>
public abstract class TypeExpr : FullNamedExpression {
- override public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
+ override public FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
{
TypeExpr t = DoResolveAsTypeStep (ec);
if (t == null)
return true;
}
- public virtual bool IsAttribute {
- get {
- return Type == TypeManager.attribute_type ||
- Type.IsSubclassOf (TypeManager.attribute_type);
- }
- }
-
protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
public virtual Type ResolveType (EmitContext ec)
}
public override string Name {
- get {
- return Type.ToString ();
- }
+ get { return Type.ToString (); }
}
public override string FullName {
- get {
- return Type.FullName != null ? Type.FullName : Type.Name;
- }
+ get { return Type.FullName; }
}
}
this.name = name;
}
+ static readonly char [] dot_array = { '.' };
protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
{
- if (type == null) {
- FullNamedExpression t = ec.DeclSpace.LookupType (name, false, Location.Null);
- if (t == null)
- return null;
- if (!(t is TypeExpr))
- return null;
- type = ((TypeExpr) t).ResolveType (ec);
+ if (type != null)
+ return this;
+
+ // If name is of the form `N.I', first lookup `N', then search a member `I' in it.
+ string rest = null;
+ string lookup_name = name;
+ int pos = name.IndexOf ('.');
+ if (pos >= 0) {
+ rest = name.Substring (pos + 1);
+ lookup_name = name.Substring (0, pos);
+ }
+
+ FullNamedExpression resolved = Namespace.Root.Lookup (ec.DeclSpace, lookup_name, Location.Null);
+
+ if (resolved != null && rest != null) {
+ // Now handle the rest of the the name.
+ string [] elements = rest.Split (dot_array);
+ string element;
+ int count = elements.Length;
+ int i = 0;
+ while (i < count && resolved != null && resolved is Namespace) {
+ Namespace ns = resolved as Namespace;
+ element = elements [i++];
+ lookup_name += "." + element;
+ resolved = ns.Lookup (ec.DeclSpace, element, Location.Null);
+ }
+
+ if (resolved != null && resolved is TypeExpr) {
+ Type t = ((TypeExpr) resolved).Type;
+ while (t != null) {
+ if (!ec.DeclSpace.CheckAccessLevel (t)) {
+ resolved = null;
+ lookup_name = t.FullName;
+ break;
+ }
+ if (i == count) {
+ type = t;
+ return this;
+ }
+ t = TypeManager.GetNestedType (t, elements [i++]);
+ }
+ }
+ }
+
+ if (resolved == null) {
+ NamespaceEntry.Error_NamespaceNotFound (loc, lookup_name);
+ return null;
}
+ if (!(resolved is TypeExpr)) {
+ resolved.Error_UnexpectedKind (ec, "type", loc);
+ return null;
+ }
+
+ type = ((TypeExpr) resolved).ResolveType (ec);
return this;
}
public override string Name {
- get {
- return name;
- }
+ get { return name; }
}
public override string FullName {
- get {
- return name;
- }
+ get { return name; }
}
}
/// Represents an "unbound generic type", ie. typeof (Foo<>).
/// See 14.5.11.
/// </summary>
- public class UnboundTypeExpression : TypeLookupExpression {
- public UnboundTypeExpression (string name)
- : base (name)
- { }
+ public class UnboundTypeExpression : TypeExpr
+ {
+ MemberName name;
+
+ public UnboundTypeExpression (MemberName name, Location l)
+ {
+ this.name = name;
+ loc = l;
+ }
+
+ protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
+ {
+ Expression expr;
+ if (name.Left != null) {
+ Expression lexpr = name.Left.GetTypeExpression ();
+ expr = new MemberAccess (lexpr, name.Basename, loc);
+ } else {
+ expr = new SimpleName (name.Basename, loc);
+ }
+
+ FullNamedExpression fne = expr.ResolveAsTypeStep (ec);
+ if (fne == null)
+ return null;
+
+ type = fne.Type;
+ return new TypeExpression (type, loc);
+ }
+
+ public override string Name {
+ get { return name.FullName; }
+ }
+
+ public override string FullName {
+ get { return name.FullName; }
+ }
}
public class TypeAliasExpression : TypeExpr {
return new TypeExpression (type, loc);
}
- public override bool CheckAccessLevel (DeclSpace ds)
+ public override bool CheckAccessLevel (DeclSpace ds)
+ {
+ return texpr.CheckAccessLevel (ds);
+ }
+
+ public override bool AsAccessible (DeclSpace ds, int flags)
+ {
+ return texpr.AsAccessible (ds, flags);
+ }
+
+ public override bool IsClass {
+ get { return texpr.IsClass; }
+ }
+
+ public override bool IsValueType {
+ get { return texpr.IsValueType; }
+ }
+
+ public override bool IsInterface {
+ get { return texpr.IsInterface; }
+ }
+
+ public override bool IsSealed {
+ get { return texpr.IsSealed; }
+ }
+ }
+
+ /// <summary>
+ /// This class denotes an expression which evaluates to a member
+ /// of a struct or a class.
+ /// </summary>
+ public abstract class MemberExpr : Expression
+ {
+ /// <summary>
+ /// The name of this member.
+ /// </summary>
+ public abstract string Name {
+ get;
+ }
+
+ /// <summary>
+ /// Whether this is an instance member.
+ /// </summary>
+ public abstract bool IsInstance {
+ get;
+ }
+
+ /// <summary>
+ /// Whether this is a static member.
+ /// </summary>
+ public abstract bool IsStatic {
+ get;
+ }
+
+ /// <summary>
+ /// The type which declares this member.
+ /// </summary>
+ public abstract Type DeclaringType {
+ get;
+ }
+
+ /// <summary>
+ /// The instance expression associated with this member, if it's a
+ /// non-static member.
+ /// </summary>
+ public Expression InstanceExpression;
+
+ public static void error176 (Location loc, string name)
{
- return texpr.CheckAccessLevel (ds);
+ Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
+ "with an instance reference, qualify it with a type name instead", name);
}
- public override bool AsAccessible (DeclSpace ds, int flags)
+
+ // TODO: possible optimalization
+ // Cache resolved constant result in FieldBuilder <-> expression map
+ public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
+ SimpleName original)
{
- return texpr.AsAccessible (ds, flags);
- }
+ //
+ // Precondition:
+ // original == null || original.Resolve (...) ==> left
+ //
- public override bool IsClass {
- get { return texpr.IsClass; }
- }
+ if (left is TypeExpr) {
+ if (!IsStatic) {
+ SimpleName.Error_ObjectRefRequired (ec, loc, Name);
+ return null;
+ }
- public override bool IsValueType {
- get { return texpr.IsValueType; }
- }
+ return this;
+ }
+
+ if (!IsInstance) {
+ if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
+ return this;
- public override bool IsInterface {
- get { return texpr.IsInterface; }
- }
+ error176 (loc, GetSignatureForError ());
+ return null;
+ }
- public override bool IsSealed {
- get { return texpr.IsSealed; }
+ InstanceExpression = left;
+
+ return this;
}
- public override bool IsAttribute {
- get { return texpr.IsAttribute; }
+ protected void EmitInstance (EmitContext ec, bool prepare_for_load)
+ {
+ if (IsStatic)
+ return;
+
+ if (InstanceExpression == EmptyExpression.Null) {
+ SimpleName.Error_ObjectRefRequired (ec, loc, Name);
+ return;
+ }
+
+ if (InstanceExpression.Type.IsValueType) {
+ if (InstanceExpression is IMemoryLocation) {
+ ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
+ } else {
+ LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
+ InstanceExpression.Emit (ec);
+ t.Store (ec);
+ t.AddressOf (ec, AddressOp.Store);
+ }
+ } else
+ InstanceExpression.Emit (ec);
+
+ if (prepare_for_load)
+ ec.ig.Emit (OpCodes.Dup);
}
}
///
/// This is a fully resolved expression that evaluates to a type
/// </summary>
- public class MethodGroupExpr : Expression, IMemberExpr {
+ public class MethodGroupExpr : MemberExpr {
public MethodBase [] Methods;
- Expression instance_expression = null;
- bool is_explicit_impl = false;
bool has_type_arguments = false;
bool identical_type_name = false;
bool is_base;
type = TypeManager.object_type;
}
- public Type DeclaringType {
+ public override Type DeclaringType {
get {
//
// We assume that the top-level type is in the end
//return Methods [0].DeclaringType;
}
}
-
- //
- // `A method group may have associated an instance expression'
- //
- public Expression InstanceExpression {
- get {
- return instance_expression;
- }
-
- set {
- instance_expression = value;
- }
- }
-
- public bool IsExplicitImpl {
- get {
- return is_explicit_impl;
- }
-
- set {
- is_explicit_impl = value;
- }
- }
public bool HasTypeArguments {
get {
}
}
- public string Name {
+ public override string GetSignatureForError ()
+ {
+ return TypeManager.CSharpSignature (Methods [0]);
+ }
+
+ public override string Name {
get {
- //return Methods [0].Name;
- return Methods [Methods.Length - 1].Name;
+ return Methods [0].Name;
}
}
- public bool IsInstance {
+ public override bool IsInstance {
get {
foreach (MethodBase mb in Methods)
if (!mb.IsStatic)
}
}
- public bool IsStatic {
+ public override bool IsStatic {
get {
foreach (MethodBase mb in Methods)
if (mb.IsStatic)
return false;
}
}
+
+ public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
+ SimpleName original)
+ {
+ if (!(left is TypeExpr) &&
+ original != null && original.IdenticalNameAndTypeName (ec, left, loc))
+ IdenticalTypeName = true;
+
+ return base.ResolveMemberAccess (ec, left, loc, original);
+ }
override public Expression DoResolve (EmitContext ec)
{
if (!IsInstance)
- instance_expression = null;
+ InstanceExpression = null;
- if (instance_expression != null) {
- instance_expression = instance_expression.DoResolve (ec);
- if (instance_expression == null)
+ if (InstanceExpression != null) {
+ InstanceExpression = InstanceExpression.DoResolve (ec);
+ if (InstanceExpression == null)
return null;
}
if (gen_params.Length != atypes.Length)
continue;
- list.Add (mi.BindGenericParameters (atypes));
+ list.Add (mi.MakeGenericMethod (atypes));
}
if (list.Count > 0) {
/// <summary>
/// Fully resolved expression that evaluates to a Field
/// </summary>
- public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
+ public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
public readonly FieldInfo FieldInfo;
- Expression instance_expr;
VariableInfo variable_info;
LocalTemporary temp;
bool prepared;
- bool is_field_initializer;
+ bool in_initializer;
+
+ public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
+ this (fi, l)
+ {
+ this.in_initializer = in_initializer;
+ }
public FieldExpr (FieldInfo fi, Location l)
{
loc = l;
}
- public string Name {
+ public override string Name {
get {
return FieldInfo.Name;
}
}
- public bool IsInstance {
+ public override bool IsInstance {
get {
return !FieldInfo.IsStatic;
}
}
- public bool IsStatic {
+ public override bool IsStatic {
get {
return FieldInfo.IsStatic;
}
}
- public Type DeclaringType {
+ public override Type DeclaringType {
get {
return FieldInfo.DeclaringType;
}
}
- public Expression InstanceExpression {
- get {
- return instance_expr;
- }
-
- set {
- instance_expr = value;
- }
+ public override string GetSignatureForError ()
+ {
+ return TypeManager.GetFullNameSignature (FieldInfo);
}
- public bool IsFieldInitializer {
+ public VariableInfo VariableInfo {
get {
- return is_field_initializer;
+ return variable_info;
}
+ }
- set {
- is_field_initializer = value;
+ public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
+ SimpleName original)
+ {
+ FieldInfo fi = FieldInfo.Mono_GetGenericFieldDefinition ();
+
+ if (fi.IsLiteral) {
+ IConstant ic = TypeManager.GetConstant (fi);
+ if (ic == null) {
+ ic = new ExternalConstant (fi);
+ TypeManager.RegisterConstant (fi, ic);
+ }
+
+ bool left_is_type = left is TypeExpr;
+ if (!left_is_type && (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
+ Report.SymbolRelatedToPreviousError (FieldInfo);
+ error176 (loc, TypeManager.GetFullNameSignature (FieldInfo));
+ return null;
+ }
+
+ if (ic.ResolveValue ())
+ ic.CheckObsoleteness (loc);
+
+ return ic.Value;
}
- }
- public VariableInfo VariableInfo {
- get {
- return variable_info;
+ bool is_emitted = fi is FieldBuilder;
+ Type t = fi.FieldType;
+
+ //
+ // Decimal constants cannot be encoded in the constant blob, and thus are marked
+ // as IsInitOnly ('readonly' in C# parlance). We get its value from the
+ // DecimalConstantAttribute metadata.
+ //
+ if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
+ object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
+ if (attrs.Length == 1)
+ return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
+ }
+
+ if (t.IsPointer && !ec.InUnsafe) {
+ UnsafeError (loc);
+ return null;
}
+
+ return base.ResolveMemberAccess (ec, left, loc, original);
}
override public Expression DoResolve (EmitContext ec)
{
+ if (ec.InRefOutArgumentResolving && FieldInfo.IsInitOnly && !ec.IsConstructor && FieldInfo.FieldType.IsValueType) {
+ if (FieldInfo.FieldType is TypeBuilder) {
+ if (FieldInfo.IsStatic)
+ Report.Error (1651, loc, "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
+ GetSignatureForError ());
+ else
+ Report.Error (1649, loc, "Members of readonly field `{0}.{1}' cannot be passed ref or out (except in a constructor)",
+ TypeManager.CSharpName (DeclaringType), Name);
+ } else {
+ if (FieldInfo.IsStatic)
+ Report.Error (199, loc, "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
+ Name);
+ else
+ Report.Error (192, loc, "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
+ Name);
+ }
+ return null;
+ }
+
if (!FieldInfo.IsStatic){
- if (instance_expr == null){
+ if (InstanceExpression == null){
//
// This can happen when referencing an instance field using
// a fully qualified type expression: TypeName.InstanceField = xxx
// 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)
+ InstanceExpression = InstanceExpression.Resolve (
+ ec, ResolveFlags.VariableOrValue | ResolveFlags.DisableFlowAnalysis);
+ if (InstanceExpression == null)
return null;
}
- ObsoleteAttribute oa;
- FieldBase f = TypeManager.GetField (FieldInfo);
- if (f != null) {
- oa = f.GetObsoleteAttribute (f.Parent);
- if (oa != null)
- AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
- // To be sure that type is external because we do not register generated fields
- } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
- oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
- if (oa != null)
- AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
+ if (!in_initializer) {
+ ObsoleteAttribute oa;
+ FieldBase f = TypeManager.GetField (FieldInfo);
+ if (f != null) {
+ f.CheckObsoleteness (loc);
+ // To be sure that type is external because we do not register generated fields
+ } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
+ oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
+ if (oa != null)
+ AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
+ }
}
- if (ec.CurrentAnonymousMethod != null){
+ AnonymousContainer am = ec.CurrentAnonymousMethod;
+ if (am != null){
if (!FieldInfo.IsStatic){
- if (ec.TypeContainer is Struct){
- Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
+ if (!am.IsIterator && (ec.TypeContainer is Struct)){
+ Report.Error (1673, loc,
+ "Anonymous methods inside structs cannot access instance members of `{0}'. Consider copying `{0}' to a local variable outside the anonymous method and using the local instead",
+ "this");
return null;
}
- ec.CaptureField (this);
- }
+ if ((am.ContainerAnonymousMethod == null) && (InstanceExpression is This))
+ ec.CaptureField (this);
+ }
}
// If the instance expression is a local variable or parameter.
- IVariable var = instance_expr as IVariable;
+ IVariable var = InstanceExpression as IVariable;
if ((var == null) || (var.VariableInfo == null))
return this;
string msg;
if (is_instance)
- msg = "Readonly field can not be assigned outside " +
- "of constructor or variable initializer";
+ msg = "A readonly field cannot be assigned to (except in a constructor or a variable initializer)";
else
- msg = "A static readonly field can only be assigned in " +
- "a static constructor";
+ msg = "A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)";
Report.Error (is_instance ? 191 : 198, loc, msg);
}
override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
- IVariable var = instance_expr as IVariable;
+ IVariable var = InstanceExpression as IVariable;
if ((var != null) && (var.VariableInfo != null))
var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
if (e == null)
return null;
- if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
- // FIXME: Provide better error reporting.
- Error (1612, "Cannot modify expression because it is not a variable.");
+ if (!FieldInfo.IsStatic && (InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation))) {
+ Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
+ InstanceExpression.GetSignatureForError ());
return null;
}
- if (!FieldInfo.IsInitOnly)
- return this;
-
FieldBase fb = TypeManager.GetField (FieldInfo);
if (fb != null)
fb.SetAssigned ();
+ if (!FieldInfo.IsInitOnly)
+ return this;
+
//
// InitOnly fields can only be assigned in constructors
//
Report_AssignToReadonly (false);
Type ctype;
- if (!is_field_initializer &&
- (ec.TypeContainer.CurrentType != null))
+ if (ec.TypeContainer.CurrentType != null)
ctype = ec.TypeContainer.CurrentType;
else
ctype = ec.ContainerType;
{
if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
Report.SymbolRelatedToPreviousError (DeclaringType);
- Report.Error (1690, loc, "Cannot call '{0}' method, property, or indexer because it is a value type member of a marshal-by-reference class", Name);
+ Report.Error (1690, loc, "Cannot call methods, properties, or indexers on `{0}' because it is a value type member of a marshal-by-reference class",
+ GetSignatureForError ());
}
}
- public bool VerifyFixed (bool is_expression)
+ public bool VerifyFixed ()
+ {
+ IVariable variable = InstanceExpression as IVariable;
+ // A variable of the form V.I is fixed when V is a fixed variable of a struct type.
+ // We defer the InstanceExpression check after the variable check to avoid a
+ // separate null check on InstanceExpression.
+ return variable != null && InstanceExpression.Type.IsValueType && variable.VerifyFixed ();
+ }
+
+ public override int GetHashCode()
+ {
+ return FieldInfo.GetHashCode ();
+ }
+
+ public override bool Equals (object obj)
{
- IVariable variable = instance_expr as IVariable;
- if ((variable == null) || !variable.VerifyFixed (true))
+ FieldExpr fe = obj as FieldExpr;
+ if (fe == null)
return false;
- return true;
+ if (FieldInfo != fe.FieldInfo)
+ return false;
+
+ if (InstanceExpression == null || fe.InstanceExpression == null)
+ return true;
+
+ return InstanceExpression.Equals (fe.InstanceExpression);
}
public void Emit (EmitContext ec, bool leave_copy)
ILGenerator ig = ec.ig;
bool is_volatile = false;
- if (FieldInfo is FieldBuilder){
- FieldBase f = TypeManager.GetField (FieldInfo);
+ FieldInfo the_fi = FieldInfo.Mono_GetGenericFieldDefinition ();
+ if (the_fi is FieldBuilder){
+ FieldBase f = TypeManager.GetField (the_fi);
if (f != null){
if ((f.ModFlags & Modifiers.VOLATILE) != 0)
is_volatile = true;
- f.status |= Field.Status.USED;
+ f.SetMemberIsUsed ();
}
}
ig.Emit (OpCodes.Ldsfld, FieldInfo);
} else {
if (!prepared)
- EmitInstance (ec);
+ EmitInstance (ec, false);
if (is_volatile)
ig.Emit (OpCodes.Volatile);
- ig.Emit (OpCodes.Ldfld, FieldInfo);
+ IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
+ if (ff != null)
+ {
+ ig.Emit (OpCodes.Ldflda, FieldInfo);
+ ig.Emit (OpCodes.Ldflda, ff.Element);
+ }
+ else {
+ ig.Emit (OpCodes.Ldfld, FieldInfo);
+ }
}
if (leave_copy) {
return;
}
- if (!is_static) {
- EmitInstance (ec);
- if (prepare_for_load)
- ig.Emit (OpCodes.Dup);
- }
+ EmitInstance (ec, prepare_for_load);
source.Emit (ec);
if (leave_copy) {
if ((f.ModFlags & Modifiers.VOLATILE) != 0)
ig.Emit (OpCodes.Volatile);
- f.status |= Field.Status.ASSIGNED;
+ f.SetAssigned ();
}
}
temp.Emit (ec);
}
- void EmitInstance (EmitContext ec)
- {
- if (instance_expr.Type.IsValueType) {
- if (instance_expr is IMemoryLocation) {
- ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
- } else {
- LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
- instance_expr.Emit (ec);
- t.Store (ec);
- t.AddressOf (ec, AddressOp.Store);
- }
- } else
- instance_expr.Emit (ec);
- }
-
public override void Emit (EmitContext ec)
{
Emit (ec, false);
FieldBase f = TypeManager.GetField (FieldInfo);
if (f != null){
if ((f.ModFlags & Modifiers.VOLATILE) != 0){
- Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
+ Report.Warning (420, 1, loc, "`{0}': A volatile fields cannot be passed using a ref or out parameter",
+ f.GetSignatureForError ());
return;
}
if ((mode & AddressOp.Store) != 0)
- f.status |= Field.Status.ASSIGNED;
+ f.SetAssigned ();
if ((mode & AddressOp.Load) != 0)
- f.status |= Field.Status.USED;
+ f.SetMemberIsUsed ();
}
}
if (FieldInfo.IsStatic){
ig.Emit (OpCodes.Ldsflda, FieldInfo);
} else {
- EmitInstance (ec);
+ EmitInstance (ec, false);
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, IMemberExpr {
+ public class PropertyExpr : MemberExpr, IAssignMethod {
public readonly PropertyInfo PropertyInfo;
//
public bool IsBase;
MethodInfo getter, setter;
bool is_static;
+
+ bool resolved;
- Expression instance_expr;
LocalTemporary temp;
bool prepared;
ResolveAccessors (ec);
}
- public string Name {
+ public override string Name {
get {
return PropertyInfo.Name;
}
}
- public bool IsInstance {
+ public override bool IsInstance {
get {
return !is_static;
}
}
- public bool IsStatic {
+ public override bool IsStatic {
get {
return is_static;
}
}
- public Type DeclaringType {
+ public override Type DeclaringType {
get {
return PropertyInfo.DeclaringType;
}
}
- //
- // The instance expression associated with this expression
- //
- public Expression InstanceExpression {
- set {
- instance_expr = value;
- }
-
- get {
- return instance_expr;
- }
- }
-
- public bool VerifyAssignable ()
+ public override string GetSignatureForError ()
{
- if (setter == null) {
- Report.Error (200, loc,
- "The property `" + PropertyInfo.Name +
- "' can not be assigned to, as it has not set accessor");
- return false;
- }
-
- return true;
+ return TypeManager.GetFullNameSignature (PropertyInfo);
}
void FindAccessors (Type invocation_type)
FindAccessors (ec.ContainerType);
if (getter != null) {
+ IMethodData md = TypeManager.GetMethod (getter);
+ if (md != null)
+ md.SetMemberIsUsed ();
+
AccessorTable [getter] = PropertyInfo;
is_static = getter.IsStatic;
}
if (setter != null) {
+ IMethodData md = TypeManager.GetMethod (setter);
+ if (md != null)
+ md.SetMemberIsUsed ();
+
AccessorTable [setter] = PropertyInfo;
is_static = setter.IsStatic;
}
bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
{
- if ((instance_expr == null) && ec.IsStatic && !is_static) {
+ if (is_static) {
+ InstanceExpression = null;
+ return true;
+ }
+
+ if (InstanceExpression == null) {
SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
return false;
}
- if (instance_expr != null) {
- instance_expr = instance_expr.DoResolve (ec);
- if (instance_expr == null)
- return false;
-
- instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
- }
+ InstanceExpression = InstanceExpression.DoResolve (ec);
+ if (InstanceExpression == null)
+ return false;
+
+ InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
- if (must_do_cs1540_check && (instance_expr != null)) {
- if ((instance_expr.Type != ec.ContainerType) &&
- ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
+ if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
+ if ((InstanceExpression.Type != ec.ContainerType) &&
+ ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
Report.Error (1540, loc, "Cannot access protected member `" +
PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
"' via a qualifier of type `" +
- TypeManager.CSharpName (instance_expr.Type) +
+ TypeManager.CSharpName (InstanceExpression.Type) +
"'; the qualifier must be of type `" +
TypeManager.CSharpName (ec.ContainerType) +
"' (or derived from it)");
return true;
}
+
+ void Error_PropertyNotFound (MethodInfo mi, bool getter)
+ {
+ // TODO: correctly we should compare arguments but it will lead to bigger changes
+ if (mi is MethodBuilder) {
+ Error_TypeDoesNotContainDefinition (loc, PropertyInfo.DeclaringType, Name);
+ return;
+ }
+
+ StringBuilder sig = new StringBuilder (TypeManager.CSharpName (mi.DeclaringType));
+ sig.Append ('.');
+ ParameterData iparams = TypeManager.GetParameterData (mi);
+ sig.Append (getter ? "get_" : "set_");
+ sig.Append (Name);
+ sig.Append (iparams.GetSignatureForError ());
+
+ Report.SymbolRelatedToPreviousError (mi);
+ Report.Error (1546, loc, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
+ Name, sig.ToString ());
+ }
override public Expression DoResolve (EmitContext ec)
{
+ if (resolved)
+ return this;
+
if (getter != null){
if (TypeManager.GetArgumentTypes (getter).Length != 0){
- Report.Error (
- 117, loc, "`{0}' does not contain a " +
- "definition for `{1}'.", getter.DeclaringType,
- Name);
+ Error_PropertyNotFound (getter, true);
return null;
}
}
//
if (setter == null)
return null;
-
- Report.Error (154, loc,
- "The property `" + PropertyInfo.Name +
- "' can not be used in " +
- "this context because it lacks a get accessor");
- return null;
+
+ if (InstanceExpression != EmptyExpression.Null) {
+ Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
+ TypeManager.GetFullNameSignature (PropertyInfo));
+ return null;
+ }
}
- bool must_do_cs1540_check;
- if (!IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
- Report.Error (122, loc, "'{0}.get' is inaccessible due to its protection level", PropertyInfo.Name);
+ bool must_do_cs1540_check = false;
+ if (getter != null &&
+ !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
+ PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
+ if (pm != null && pm.HasCustomAccessModifier) {
+ Report.SymbolRelatedToPreviousError (pm);
+ Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
+ TypeManager.CSharpSignature (getter));
+ }
+ else
+ ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter));
return null;
}
//
// Only base will allow this invocation to happen.
//
- if (IsBase && getter.IsAbstract){
- Report.Error (205, loc, "Cannot call an abstract base property: " +
- PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
+ if (IsBase && getter.IsAbstract) {
+ Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
return null;
}
+ if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
+ UnsafeError (loc);
+ return null;
+ }
+
+ resolved = true;
+
return this;
}
if (getter == null)
return null;
- Report.Error (154, loc,
- "The property `" + PropertyInfo.Name +
- "' can not be used in " +
- "this context because it lacks a set accessor");
+ Report.Error (200, loc, " Property or indexer `{0}' cannot be assigned to (it is read only)",
+ TypeManager.GetFullNameSignature (PropertyInfo));
return null;
}
if (TypeManager.GetArgumentTypes (setter).Length != 1){
- Report.Error (
- 117, loc, "`{0}' does not contain a " +
- "definition for `{1}'.", getter.DeclaringType,
- Name);
+ Error_PropertyNotFound (setter, false);
return null;
}
bool must_do_cs1540_check;
if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
- Report.Error (122, loc, "'{0}.set' is inaccessible due to its protection level", PropertyInfo.Name);
+ PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
+ if (pm != null && pm.HasCustomAccessModifier) {
+ Report.SymbolRelatedToPreviousError (pm);
+ Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
+ TypeManager.CSharpSignature (setter));
+ }
+ else
+ ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter));
return null;
}
// Only base will allow this invocation to happen.
//
if (IsBase && setter.IsAbstract){
- Report.Error (205, loc, "Cannot call an abstract base property: " +
- PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
+ Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
return null;
}
//
// Check that we are not making changes to a temporary memory location
//
- if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
- // FIXME: Provide better error reporting.
- Error (1612, "Cannot modify expression because it is not a variable.");
+ if (InstanceExpression != null && InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation)) {
+ Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
+ InstanceExpression.GetSignatureForError ());
return null;
}
return this;
}
-
-
public override void Emit (EmitContext ec)
{
Emit (ec, false);
}
- void EmitInstance (EmitContext ec)
- {
- if (is_static)
- return;
-
- if (instance_expr.Type.IsValueType) {
- if (instance_expr is IMemoryLocation) {
- ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
- } else {
- LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
- instance_expr.Emit (ec);
- t.Store (ec);
- t.AddressOf (ec, AddressOp.Store);
- }
- } else
- instance_expr.Emit (ec);
-
- if (prepared)
- ec.ig.Emit (OpCodes.Dup);
- }
-
-
public void Emit (EmitContext ec, bool leave_copy)
{
if (!prepared)
- EmitInstance (ec);
+ EmitInstance (ec, false);
//
// Special case: length of single dimension array property is turned into ldlen
//
if ((getter == TypeManager.system_int_array_get_length) ||
(getter == TypeManager.int_array_get_length)){
- Type iet = instance_expr.Type;
+ Type iet = InstanceExpression.Type;
//
// System.Array.Length can be called, but the Type does not
{
prepared = prepare_for_load;
- EmitInstance (ec);
+ EmitInstance (ec, prepare_for_load);
source.Emit (ec);
if (leave_copy) {
if (temp != null)
temp.Emit (ec);
}
-
- override public void EmitStatement (EmitContext ec)
- {
- Emit (ec);
- ec.ig.Emit (OpCodes.Pop);
- }
}
/// <summary>
/// Fully resolved expression that evaluates to an Event
/// </summary>
- public class EventExpr : Expression, IMemberExpr {
+ public class EventExpr : MemberExpr {
public readonly EventInfo EventInfo;
- Expression instance_expr;
bool is_static;
MethodInfo add_accessor, remove_accessor;
type = EventInfo.EventHandlerType;
}
- public string Name {
+ public override string Name {
get {
return EventInfo.Name;
}
}
- public bool IsInstance {
+ public override bool IsInstance {
get {
return !is_static;
}
}
- public bool IsStatic {
+ public override bool IsStatic {
get {
return is_static;
}
}
- public Type DeclaringType {
+ public override Type DeclaringType {
get {
return EventInfo.DeclaringType;
}
}
- public Expression InstanceExpression {
- get {
- return instance_expr;
- }
+ public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
+ SimpleName original)
+ {
+ //
+ // If the event is local to this class, we transform ourselves into a FieldExpr
+ //
- set {
- instance_expr = value;
+ if (EventInfo.DeclaringType == ec.ContainerType ||
+ TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
+ MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
+
+ if (mi != null) {
+ MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
+
+ if (ml == null) {
+ Report.Error (-200, loc, "Internal error!!");
+ return null;
+ }
+
+ InstanceExpression = null;
+
+ return ml.ResolveMemberAccess (ec, left, loc, original);
+ }
}
+
+ return base.ResolveMemberAccess (ec, left, loc, original);
}
+
bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
{
- if ((instance_expr == null) && ec.IsStatic && !is_static) {
+ if (is_static) {
+ InstanceExpression = null;
+ return true;
+ }
+
+ if (InstanceExpression == null) {
SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
return false;
}
- if (instance_expr != null) {
- instance_expr = instance_expr.DoResolve (ec);
- if (instance_expr == null)
- return false;
- }
+ InstanceExpression = InstanceExpression.DoResolve (ec);
+ if (InstanceExpression == null)
+ return false;
//
// This is using the same mechanism as the CS1540 check in PropertyExpr.
// However, in the Event case, we reported a CS0122 instead.
//
- if (must_do_cs1540_check && (instance_expr != null)) {
- if ((instance_expr.Type != ec.ContainerType) &&
- ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
- Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
- DeclaringType.Name + "." + EventInfo.Name);
-
+ if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
+ if ((InstanceExpression.Type != ec.ContainerType) &&
+ ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
+ ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
return false;
}
}
return true;
}
- public override Expression DoResolve (EmitContext ec)
+ public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
{
- if (instance_expr != null) {
- instance_expr = instance_expr.DoResolve (ec);
- if (instance_expr == null)
- return null;
- }
+ return DoResolve (ec);
+ }
+ public override Expression DoResolve (EmitContext ec)
+ {
bool must_do_cs1540_check;
- if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check)
- && IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
-
- Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
- DeclaringType.Name + "." + EventInfo.Name);
- return null;
+ if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
+ IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
+ ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
+ return null;
}
if (!InstanceResolve (ec, must_do_cs1540_check))
public override void Emit (EmitContext ec)
{
- if (instance_expr is This)
- Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate", Name);
+ if (InstanceExpression is This)
+ Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=", GetSignatureForError ());
else
Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
"(except on the defining type)", Name);
}
+ public override string GetSignatureForError ()
+ {
+ return TypeManager.CSharpSignature (EventInfo);
+ }
+
public void EmitAddOrRemove (EmitContext ec, Expression source)
{
BinaryDelegate source_del = (BinaryDelegate) source;
if (source_del.IsAddition)
Invocation.EmitCall (
- ec, false, IsStatic, instance_expr, add_accessor, args, loc);
+ ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
else
Invocation.EmitCall (
- ec, false, IsStatic, instance_expr, remove_accessor, args, loc);
+ ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);
}
}
}