Add more incomplete statements to AST. Fixes #4361.
[mono.git] / mcs / mcs / attribute.cs
index 92ce35e8bfae13c9d0c6f44f69457a87a15644c1..ae9627e93be4b709c507235b19a347622c154bc1 100644 (file)
@@ -8,14 +8,11 @@
 //
 // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
 // Copyright 2003-2008 Novell, Inc.
+// Copyright 2011 Xamarin Inc
 //
 
 using System;
-using System.Diagnostics;
-using System.Collections;
-using System.Collections.Specialized;
-using System.Reflection;
-using System.Reflection.Emit;
+using System.Collections.Generic;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
 using System.Security; 
@@ -23,49 +20,61 @@ using System.Security.Permissions;
 using System.Text;
 using System.IO;
 
+#if STATIC
+using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
+using BadImageFormat = IKVM.Reflection.BadImageFormatException;
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
+using BadImageFormat = System.BadImageFormatException;
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
 namespace Mono.CSharp {
 
        /// <summary>
        ///   Base class for objects that can have Attributes applied to them.
        /// </summary>
        public abstract class Attributable {
-               /// <summary>
-               ///   Attributes for this type
-               /// </summary>
+               //
+               // Holds all attributes attached to this element
+               //
                protected Attributes attributes;
 
-               public Attributable (Attributes attrs)
+               public void AddAttributes (Attributes attrs, IMemberContext context)
                {
-                       if (attrs != null)
-                               OptAttributes = attrs;
+                       if (attrs == null)
+                               return;
+
+                       if (attributes == null)
+                               attributes = attrs;
+                       else
+                               attributes.AddAttributes (attrs.Attrs);
+
+                       attrs.AttachTo (this, context);
                }
 
-               public Attributes OptAttributes 
-               {
+               public Attributes OptAttributes {
                        get {
                                return attributes;
                        }
                        set {
                                attributes = value;
-
-                               if (attributes != null) {
-                                       attributes.AttachTo (this);
-                               }
                        }
                }
 
                /// <summary>
                /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
                /// </summary>
-               public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
+               public abstract void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa);
 
                /// <summary>
                /// Returns one AttributeTarget for this element.
                /// </summary>
                public abstract AttributeTargets AttributeTargets { get; }
 
-               public abstract IResolveContext ResolveContext { get; }
-
                public abstract bool IsClsComplianceRequired ();
 
                /// <summary>
@@ -75,118 +84,159 @@ namespace Mono.CSharp {
                public abstract string[] ValidAttributeTargets { get; }
        };
 
-       public class Attribute : Expression
+       public class Attribute
        {
                public readonly string ExplicitTarget;
                public AttributeTargets Target;
+               readonly ATypeNameExpression expression;
 
-               // TODO: remove this member
-               public readonly string    Name;
-               public readonly Expression LeftExpr;
-               public readonly string Identifier;
-
-               ArrayList PosArguments;
-               ArrayList NamedArguments;
+               Arguments pos_args, named_args;
 
                bool resolve_error;
+               bool arg_resolved;
                readonly bool nameEscaped;
+               readonly Location loc;
+               public TypeSpec Type;   
+
+               //
+               // An attribute can be attached to multiple targets (e.g. multiple fields)
+               //
+               Attributable[] targets;
 
-               // It can contain more onwers when the attribute is applied to multiple fiels.
-               protected Attributable[] owners;
+               //
+               // A member context for the attribute, it's much easier to hold it here
+               // than trying to pull it during resolve
+               //
+               IMemberContext context;
 
-               static readonly AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
-               static Assembly orig_sec_assembly;
+               public static readonly AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
                public static readonly object[] EmptyObject = new object [0];
 
-               // non-null if named args present after Resolve () is called
-               PropertyInfo [] prop_info_arr;
-               FieldInfo [] field_info_arr;
-               object [] field_values_arr;
-               object [] prop_values_arr;
-               object [] pos_values;
+               List<KeyValuePair<MemberExpr, NamedArgument>> named_values;
 
-               static PtrHashtable usage_attr_cache;
-               // Cache for parameter-less attributes
-               static PtrHashtable att_cache;
-               
-               public Attribute (string target, Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped)
+               public Attribute (string target, ATypeNameExpression expr, Arguments[] args, Location loc, bool nameEscaped)
                {
-                       LeftExpr = left_expr;
-                       Identifier = identifier;
-                       Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
+                       this.expression = expr;
                        if (args != null) {
-                               PosArguments = (ArrayList)args [0];
-                               NamedArguments = (ArrayList)args [1];                           
+                               pos_args = args[0];
+                               named_args = args[1];
                        }
                        this.loc = loc;
                        ExplicitTarget = target;
                        this.nameEscaped = nameEscaped;
                }
 
-               public Attribute Clone ()
-               {
-                       Attribute a = new Attribute (ExplicitTarget, LeftExpr, Identifier, null, loc, nameEscaped);
-                       a.PosArguments = PosArguments;
-                       a.NamedArguments = NamedArguments;
-                       return a;
+               public Location Location {
+                       get {
+                               return loc;
+                       }
+               }
+
+               public Arguments NamedArguments {
+                       get {
+                               return named_args;
+                       }
+               }
+
+               public Arguments PositionalArguments {
+                       get {
+                               return pos_args;
+                       }
+               }
+
+               public ATypeNameExpression TypeExpression {
+                       get {
+                               return expression;
+                       }
                }
 
-               static Attribute ()
+               void AddModuleCharSet (ResolveContext rc)
                {
-                       Reset ();
+                       const string dll_import_char_set = "CharSet";
+
+                       //
+                       // Only when not customized by user
+                       //
+                       if (HasField (dll_import_char_set))
+                               return;
+
+                       if (!rc.Module.PredefinedTypes.CharSet.Define ()) {
+                               return;
+                       }
+
+                       if (NamedArguments == null)
+                               named_args = new Arguments (1);
+
+                       var value = Constant.CreateConstant (rc.Module.PredefinedTypes.CharSet.TypeSpec, rc.Module.DefaultCharSet, Location);
+                       NamedArguments.Add (new NamedArgument (dll_import_char_set, loc, value));
                }
 
-               public static void Reset ()
+               public Attribute Clone ()
                {
-                       usage_attr_cache = new PtrHashtable ();
-                       att_cache = new PtrHashtable ();
+                       Attribute a = new Attribute (ExplicitTarget, expression, null, loc, nameEscaped);
+                       a.pos_args = pos_args;
+                       a.named_args = NamedArguments;
+                       return a;
                }
 
-               public virtual void AttachTo (Attributable owner)
+               //
+               // When the same attribute is attached to multiple fiels
+               // we use @target field as a list of targets. The attribute
+               // has to be resolved only once but emitted for each target.
+               //
+               public void AttachTo (Attributable target, IMemberContext context)
                {
-                       if (this.owners == null) {
-                               this.owners = new Attributable[1] { owner };
+                       if (this.targets == null) {
+                               this.targets = new Attributable[] { target };
+                               this.context = context;
+                               return;
+                       }
+
+                       // When re-attaching global attributes
+                       if (context is NamespaceContainer) {
+                               this.targets[0] = target;
+                               this.context = context;
                                return;
                        }
 
-                       // When the same attribute is attached to multiple fiels
-                       // we use this extra_owners as a list of owners. The attribute
-                       // then can be removed because will be emitted when first owner
-                       // is served
-                       Attributable[] new_array = new Attributable [this.owners.Length + 1];
-                       owners.CopyTo (new_array, 0);
-                       new_array [owners.Length] = owner;
-                       this.owners = new_array;
-                       owner.OptAttributes = null;
+                       // Resize target array
+                       Attributable[] new_array = new Attributable [this.targets.Length + 1];
+                       targets.CopyTo (new_array, 0);
+                       new_array [targets.Length] = target;
+                       this.targets = new_array;
+
+                       // No need to update context, different targets cannot have
+                       // different contexts, it's enough to remove same attributes
+                       // from secondary members.
+
+                       target.OptAttributes = null;
                }
 
-               void Error_InvalidNamedArgument (string name)
+               public ResolveContext CreateResolveContext ()
                {
-                       Report.Error (617, Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
+                       return new ResolveContext (context, ResolveContext.Options.ConstantScope);
+               }
+
+               static void Error_InvalidNamedArgument (ResolveContext rc, NamedArgument name)
+               {
+                       rc.Report.Error (617, name.Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
                                      "must be fields which are not readonly, static, const or read-write properties which are " +
                                      "public and not static",
-                             name);
+                             name.Name);
                }
 
-               void Error_InvalidNamedAgrumentType (string name)
+               static void Error_InvalidNamedArgumentType (ResolveContext rc, NamedArgument name)
                {
-                       Report.Error (655, Location, "`{0}' is not a valid named attribute argument because it is not a valid " +
-                                     "attribute parameter type", name);
+                       rc.Report.Error (655, name.Location,
+                               "`{0}' is not a valid named attribute argument because it is not a valid attribute parameter type",
+                               name.Name);
                }
 
-               public static void Error_AttributeArgumentNotValid (Location loc)
+               public static void Error_AttributeArgumentIsDynamic (IMemberContext context, Location loc)
                {
-                       Report.Error (182, loc,
-                                     "An attribute argument must be a constant expression, typeof " +
-                                     "expression or array creation expression");
+                       context.Module.Compiler.Report.Error (1982, loc, "An attribute argument cannot be dynamic expression");
                }
                
-               static void Error_TypeParameterInAttribute (Location loc)
-               {
-                       Report.Error (
-                               -202, loc, "Can not use a type parameter in an attribute");
-               }
-
                public void Error_MissingGuidAttribute ()
                {
                        Report.Error (596, Location, "The Guid attribute must be specified with the ComImport attribute");
@@ -197,6 +247,11 @@ namespace Mono.CSharp {
                        Report.Error (1112, Location, "Do not use `{0}' directly. Use parameter modifier `this' instead", GetSignatureForError ());
                }
 
+               public void Error_MisusedDynamicAttribute ()
+               {
+                       Report.Error (1970, loc, "Do not use `{0}' directly. Use `dynamic' keyword instead", GetSignatureForError ());
+               }
+
                /// <summary>
                /// This is rather hack. We report many emit attribute error with same error to be compatible with
                /// csc. But because csc has to report them this way because error came from ilasm we needn't.
@@ -214,37 +269,8 @@ namespace Mono.CSharp {
 
                Attributable Owner {
                        get {
-                               return owners [0];
-                       }
-               }
-
-               protected virtual TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
-               {
-                       return expr.ResolveAsTypeTerminal (ec, silent);
-               }
-
-               Type ResolvePossibleAttributeType (string name, bool silent, ref bool is_attr)
-               {
-                       IResolveContext rc = Owner.ResolveContext;
-
-                       TypeExpr te;
-                       if (LeftExpr == null) {
-                               te = ResolveAsTypeTerminal (new SimpleName (name, Location), rc, silent);
-                       } else {
-                               te = ResolveAsTypeTerminal (new MemberAccess (LeftExpr, name), rc, silent);
-                       }
-
-                       if (te == null)
-                               return null;
-
-                       Type t = te.Type;
-                       if (TypeManager.IsSubclassOf (t, TypeManager.attribute_type)) {
-                               is_attr = true;
-                       } else if (!silent) {
-                               Report.SymbolRelatedToPreviousError (t);
-                               Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
+                               return targets [0];
                        }
-                       return t;
                }
 
                /// <summary>
@@ -252,16 +278,41 @@ namespace Mono.CSharp {
                /// </summary>
                void ResolveAttributeType ()
                {
-                       bool t1_is_attr = false;
-                       Type t1 = ResolvePossibleAttributeType (Identifier, true, ref t1_is_attr);
+                       SessionReportPrinter resolve_printer = new SessionReportPrinter ();
+                       ReportPrinter prev_recorder = Report.SetPrinter (resolve_printer);
 
+                       bool t1_is_attr = false;
                        bool t2_is_attr = false;
-                       Type t2 = nameEscaped ? null :
-                               ResolvePossibleAttributeType (Identifier + "Attribute", true, ref t2_is_attr);
+                       TypeSpec t1, t2;
+                       ATypeNameExpression expanded = null;
+
+                       // TODO: Additional warnings such as CS0436 are swallowed because we don't
+                       // print on success
+
+                       try {
+                               t1 = expression.ResolveAsType (context);
+                               if (t1 != null)
+                                       t1_is_attr = t1.IsAttribute;
+
+                               resolve_printer.EndSession ();
 
-                       if (t1_is_attr && t2_is_attr) {
-                               Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. " +
-                                             "Use either `@{0}' or `{0}Attribute'", GetSignatureForError ());
+                               if (nameEscaped) {
+                                       t2 = null;
+                               } else {
+                                       expanded = (ATypeNameExpression) expression.Clone (null);
+                                       expanded.Name += "Attribute";
+
+                                       t2 = expanded.ResolveAsType (context);
+                                       if (t2 != null)
+                                               t2_is_attr = t2.IsAttribute;
+                               }
+                       } finally {
+                               context.Module.Compiler.Report.SetPrinter (prev_recorder);
+                       }
+
+                       if (t1_is_attr && t2_is_attr && t1 != t2) {
+                               Report.Error (1614, Location, "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}Attribute'",
+                                       GetSignatureForError (), expression.GetSignatureForError (), expanded.GetSignatureForError ());
                                resolve_error = true;
                                return;
                        }
@@ -276,84 +327,102 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       if (t1 == null && t2 == null)
-                               ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
-                       if (t1 != null)
-                               ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
-                       if (t2 != null)
-                               ResolvePossibleAttributeType (Identifier + "Attribute", false, ref t2_is_attr);
-
                        resolve_error = true;
+
+                       if (t1 != null) {
+                               resolve_printer.Merge (prev_recorder);
+
+                               Report.SymbolRelatedToPreviousError (t1);
+                               Report.Error (616, Location, "`{0}': is not an attribute class", t1.GetSignatureForError ());
+                               return;
+                       }
+
+                       if (t2 != null) {
+                               Report.SymbolRelatedToPreviousError (t2);
+                               Report.Error (616, Location, "`{0}': is not an attribute class", t2.GetSignatureForError ());
+                               return;
+                       }
+
+                       resolve_printer.Merge (prev_recorder);
                }
 
-               public virtual Type ResolveType ()
+               public TypeSpec ResolveType ()
                {
                        if (Type == null && !resolve_error)
                                ResolveAttributeType ();
                        return Type;
                }
 
-               public override string GetSignatureForError ()
+               public string GetSignatureForError ()
                {
                        if (Type != null)
                                return TypeManager.CSharpName (Type);
 
-                       return LeftExpr == null ? Identifier : LeftExpr.GetSignatureForError () + "." + Identifier;
+                       return expression.GetSignatureForError ();
                }
 
                public bool HasSecurityAttribute {
                        get {
-                               return TypeManager.security_attr_type != null &&
-                               TypeManager.IsSubclassOf (type, TypeManager.security_attr_type);
+                               PredefinedAttribute pa = context.Module.PredefinedAttributes.Security;
+                               return pa.IsDefined && TypeSpec.IsBaseClass (Type, pa.TypeSpec, false);
                        }
                }
 
                public bool IsValidSecurityAttribute ()
                {
-                       return HasSecurityAttribute && IsSecurityActionValid (false);
+                       return HasSecurityAttribute && IsSecurityActionValid ();
                }
 
-               static bool IsValidArgumentType (Type t)
+               static bool IsValidArgumentType (TypeSpec t)
                {
-                       if (t.IsArray)
-                               t = TypeManager.GetElementType (t);
+                       if (t.IsArray) {
+                               var ac = (ArrayContainer) t;
+                               if (ac.Rank > 1)
+                                       return false;
 
-                       return t == TypeManager.string_type ||
-                               TypeManager.IsPrimitiveType (t) ||
-                               TypeManager.IsEnumType (t) ||
-                               t == TypeManager.object_type ||
-                               t == TypeManager.type_type;
-               }
+                               t = ac.Element;
+                       }
+
+                       switch (t.BuiltinType) {
+                       case BuiltinTypeSpec.Type.Int:
+                       case BuiltinTypeSpec.Type.UInt:
+                       case BuiltinTypeSpec.Type.Long:
+                       case BuiltinTypeSpec.Type.ULong:
+                       case BuiltinTypeSpec.Type.Float:
+                       case BuiltinTypeSpec.Type.Double:
+                       case BuiltinTypeSpec.Type.Char:
+                       case BuiltinTypeSpec.Type.Short:
+                       case BuiltinTypeSpec.Type.Bool:
+                       case BuiltinTypeSpec.Type.SByte:
+                       case BuiltinTypeSpec.Type.Byte:
+                       case BuiltinTypeSpec.Type.UShort:
+
+                       case BuiltinTypeSpec.Type.String:
+                       case BuiltinTypeSpec.Type.Object:
+                       case BuiltinTypeSpec.Type.Dynamic:
+                       case BuiltinTypeSpec.Type.Type:
+                               return true;
+                       }
 
-               [Conditional ("GMCS_SOURCE")]
-               void ApplyModuleCharSet ()
-               {
-                       if (Type != TypeManager.dllimport_type)
-                               return;
+                       return t.IsEnum;
+               }
 
-                       if (!CodeGen.Module.HasDefaultCharSet)
-                               return;
+               // TODO: Don't use this ambiguous value
+               public string Name {
+                       get { return expression.Name; }
+               }
 
-                       const string CharSetEnumMember = "CharSet";
-                       if (NamedArguments == null) {
-                               NamedArguments = new ArrayList (1);
-                       } else {
-                               foreach (DictionaryEntry de in NamedArguments) {
-                                       if ((string)de.Key == CharSetEnumMember)
-                                               return;
-                               }
-                       }
-                       
-                       NamedArguments.Add (new DictionaryEntry (CharSetEnumMember,
-                               new Argument (Constant.CreateConstant (typeof (CharSet), CodeGen.Module.DefaultCharSet, Location))));
-               }
+               public Report Report {
+                       get { return context.Module.Compiler.Report; }
+               }
 
-               public CustomAttributeBuilder Resolve ()
+               public MethodSpec Resolve ()
                {
                        if (resolve_error)
                                return null;
 
                        resolve_error = true;
+                       arg_resolved = true;
 
                        if (Type == null) {
                                ResolveAttributeType ();
@@ -366,280 +435,151 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (Type);
+                       ObsoleteAttribute obsolete_attr = Type.GetAttributeObsolete ();
                        if (obsolete_attr != null) {
-                               AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location);
-                       }
-
-                       if (PosArguments == null && NamedArguments == null) {
-                               object o = att_cache [Type];
-                               if (o != null) {
-                                       resolve_error = false;
-                                       return (CustomAttributeBuilder)o;
-                               }
-                       }
-
-                       Attributable owner = Owner;
-                       DeclSpace ds = owner.ResolveContext as DeclSpace;
-                       if (ds == null)
-                               ds = owner.ResolveContext.DeclContainer;
-                       
-                       EmitContext ec = new EmitContext (owner.ResolveContext, ds, owner.ResolveContext.DeclContainer,
-                               Location, null, typeof (Attribute), owner.ResolveContext.DeclContainer.ModFlags, false);
-                       ec.IsAnonymousMethodAllowed = false;
-
-                       ConstructorInfo ctor = ResolveConstructor (ec);
-                       if (ctor == null) {
-                               if (Type is TypeBuilder && 
-                                   TypeManager.LookupDeclSpace (Type).MemberCache == null)
-                                       // The attribute type has been DefineType'd, but not Defined.  Let's not treat it as an error.
-                                       // It'll be resolved again when the attached-to entity is emitted.
-                                       resolve_error = false;
-                               return null;
+                               AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location, Report);
                        }
 
-                       ApplyModuleCharSet ();
-
-                       CustomAttributeBuilder cb;
-                       try {
-                               // SRE does not allow private ctor but we want to report all source code errors
-                               if (ctor.IsPrivate)
-                                       return null;
-
-                               if (NamedArguments == null) {
-                                       cb = new CustomAttributeBuilder (ctor, pos_values);
-
-                                       if (pos_values.Length == 0)
-                                               att_cache.Add (Type, cb);
+                       ResolveContext rc = null;
 
-                                       resolve_error = false;
-                                       return cb;
-                               }
-
-                               if (!ResolveNamedArguments (ec)) {
+                       MethodSpec ctor;
+                       // Try if the attribute is simple and has been resolved before
+                       if (pos_args != null || !context.Module.AttributeConstructorCache.TryGetValue (Type, out ctor)) {
+                               rc = CreateResolveContext ();
+                               ctor = ResolveConstructor (rc);
+                               if (ctor == null) {
                                        return null;
                                }
 
-                               cb = new CustomAttributeBuilder (ctor, pos_values,
-                                               prop_info_arr, prop_values_arr,
-                                               field_info_arr, field_values_arr);
-
-                               resolve_error = false;
-                               return cb;
-                       }
-                       catch (Exception) {
-                               Error_AttributeArgumentNotValid (Location);
-                               return null;
-                       }
-               }
-
-               protected virtual ConstructorInfo ResolveConstructor (EmitContext ec)
-               {
-                       if (PosArguments != null) {
-                               for (int i = 0; i < PosArguments.Count; i++) {
-                                       Argument a = (Argument) PosArguments [i];
-
-                                       if (!a.Resolve (ec, Location))
-                                               return null;
-                               }
+                               if (pos_args == null && ctor.Parameters.IsEmpty)
+                                       context.Module.AttributeConstructorCache.Add (Type, ctor);
                        }
-                       
-                       MethodGroupExpr mg = MemberLookupFinal (ec, ec.ContainerType,
-                               Type, ".ctor", MemberTypes.Constructor,
-                               BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
-                               Location) as MethodGroupExpr;
 
-                       if (mg == null)
-                               return null;
+                       //
+                       // Add [module: DefaultCharSet] to all DllImport import attributes
+                       //
+                       var module = context.Module;
+                       if ((Type == module.PredefinedAttributes.DllImport || Type == module.PredefinedAttributes.UnmanagedFunctionPointer) && module.HasDefaultCharSet) {
+                               if (rc == null)
+                                       rc = CreateResolveContext ();
 
-                       mg = mg.OverloadResolve (ec, ref PosArguments, false, Location);
-                       if (mg == null)
-                               return null;
-                       
-                       ConstructorInfo constructor = (ConstructorInfo)mg;
-                       if (PosArguments == null) {
-                               pos_values = EmptyObject;
-                               return constructor;
+                               AddModuleCharSet (rc);
                        }
 
-                       AParametersCollection pd = TypeManager.GetParameterData (constructor);
-
-                       int pos_arg_count = PosArguments.Count;
-                       pos_values = new object [pos_arg_count];
-                       for (int j = 0; j < pos_arg_count; ++j) {
-                               Argument a = (Argument) PosArguments [j];
-
-                               if (!a.Expr.GetAttributableValue (ec, a.Type, out pos_values [j]))
-                                       return null;
-                       }
+                       if (NamedArguments != null) {
+                               if (rc == null)
+                                       rc = CreateResolveContext ();
 
-                       // Here we do the checks which should be done by corlib or by runtime.
-                       // However Zoltan doesn't like it and every Mono compiler has to do it again.
-                       
-                       if (Type == TypeManager.guid_attr_type) {
-                               try {
-                                       new Guid ((string)pos_values [0]);
-                               }
-                               catch (Exception e) {
-                                       Error_AttributeEmitError (e.Message);
+                               if (!ResolveNamedArguments (rc))
                                        return null;
-                               }
                        }
 
-                       if (Type == TypeManager.attribute_usage_type && (int)pos_values [0] == 0) {
-                               Report.Error (591, Location, "Invalid value for argument to `System.AttributeUsage' attribute");
-                               return null;
-                       }
+                       resolve_error = false;
+                       return ctor;
+               }
 
-                       if (Type == TypeManager.indexer_name_type || Type == TypeManager.conditional_attribute_type) {
-                               string v = pos_values [0] as string;
-                               if (!Tokenizer.IsValidIdentifier (v) || Tokenizer.IsKeyword (v)) {
-                                       Report.Error (633, ((Argument)PosArguments[0]).Expr.Location,
-                                               "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
+               MethodSpec ResolveConstructor (ResolveContext ec)
+               {
+                       if (pos_args != null) {
+                               bool dynamic;
+                               pos_args.Resolve (ec, out dynamic);
+                               if (dynamic) {
+                                       Error_AttributeArgumentIsDynamic (ec.MemberContext, loc);
                                        return null;
                                }
                        }
 
-                       if (Type == TypeManager.methodimpl_attr_type && pos_values.Length == 1 &&
-                               pd.Types [0] == TypeManager.short_type &&
-                               !System.Enum.IsDefined (typeof (MethodImplOptions), pos_values [0].ToString ())) {
-                               Error_AttributeEmitError ("Incorrect argument value.");
-                               return null;
-                       }
-
-                       return constructor;
+                       return Expression.ConstructorLookup (ec, Type, ref pos_args, loc);
                }
 
-               protected virtual bool ResolveNamedArguments (EmitContext ec)
+               bool ResolveNamedArguments (ResolveContext ec)
                {
                        int named_arg_count = NamedArguments.Count;
+                       var seen_names = new List<string> (named_arg_count);
 
-                       ArrayList field_infos = new ArrayList (named_arg_count);
-                       ArrayList prop_infos  = new ArrayList (named_arg_count);
-                       ArrayList field_values = new ArrayList (named_arg_count);
-                       ArrayList prop_values = new ArrayList (named_arg_count);
-
-                       ArrayList seen_names = new ArrayList(named_arg_count);
+                       named_values = new List<KeyValuePair<MemberExpr, NamedArgument>> (named_arg_count);
                        
-                       foreach (DictionaryEntry de in NamedArguments) {
-                               string member_name = (string) de.Key;
-
-                               if (seen_names.Contains(member_name)) {
-                                       Report.Error(643, Location, "'{0}' duplicate named attribute argument", member_name);
-                                       return false;
-                               }                               
-                               seen_names.Add(member_name);
+                       foreach (NamedArgument a in NamedArguments) {
+                               string name = a.Name;
+                               if (seen_names.Contains (name)) {
+                                       ec.Report.Error (643, a.Location, "Duplicate named attribute `{0}' argument", name);
+                                       continue;
+                               }                       
+       
+                               seen_names.Add (name);
 
-                               Argument a = (Argument) de.Value;
-                               if (!a.Resolve (ec, Location))
-                                       return false;
+                               a.Resolve (ec);
 
-                               Expression member = Expression.MemberLookup (
-                                       ec.ContainerType, Type, member_name,
-                                       MemberTypes.Field | MemberTypes.Property,
-                                       BindingFlags.Public | BindingFlags.Instance,
-                                       Location);
+                               Expression member = Expression.MemberLookup (ec, false, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
 
                                if (member == null) {
-                                       member = Expression.MemberLookup (ec.ContainerType, Type, member_name,
-                                               MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
-                                               Location);
+                                       member = Expression.MemberLookup (ec, true, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
 
                                        if (member != null) {
-                                               Report.SymbolRelatedToPreviousError (member.Type);
-                                               Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
+                                               // TODO: ec.Report.SymbolRelatedToPreviousError (member);
+                                               Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
                                                return false;
                                        }
                                }
 
                                if (member == null){
-                                       Expression.Error_TypeDoesNotContainDefinition (Location, Type, member_name);
+                                       Expression.Error_TypeDoesNotContainDefinition (ec, Location, Type, name);
                                        return false;
                                }
                                
                                if (!(member is PropertyExpr || member is FieldExpr)) {
-                                       Error_InvalidNamedArgument (member_name);
-                                       return false;
-                               }
-
-                               if (a.Expr is TypeParameterExpr){
-                                       Error_TypeParameterInAttribute (Location);
+                                       Error_InvalidNamedArgument (ec, a);
                                        return false;
                                }
 
                                ObsoleteAttribute obsolete_attr;
 
                                if (member is PropertyExpr) {
-                                       PropertyInfo pi = ((PropertyExpr) member).PropertyInfo;
+                                       var pi = ((PropertyExpr) member).PropertyInfo;
 
-                                       if (!pi.CanWrite || !pi.CanRead) {
-                                               Report.SymbolRelatedToPreviousError (pi);
-                                               Error_InvalidNamedArgument (member_name);
+                                       if (!pi.HasSet || !pi.HasGet || pi.IsStatic || !pi.Get.IsPublic || !pi.Set.IsPublic) {
+                                               ec.Report.SymbolRelatedToPreviousError (pi);
+                                               Error_InvalidNamedArgument (ec, a);
                                                return false;
                                        }
 
                                        if (!IsValidArgumentType (member.Type)) {
-                                               Report.SymbolRelatedToPreviousError (pi);
-                                               Error_InvalidNamedAgrumentType (member_name);
+                                               ec.Report.SymbolRelatedToPreviousError (pi);
+                                               Error_InvalidNamedArgumentType (ec, a);
                                                return false;
                                        }
 
-                                       object value;
-                                       if (!a.Expr.GetAttributableValue (ec, member.Type, out value))
-                                               return false;
-
-                                       PropertyBase pb = TypeManager.GetProperty (pi);
-                                       if (pb != null)
-                                               obsolete_attr = pb.GetObsoleteAttribute ();
-                                       else
-                                               obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (pi);
-
-                                       prop_values.Add (value);
-                                       prop_infos.Add (pi);
-                                       
+                                       obsolete_attr = pi.GetAttributeObsolete ();
+                                       pi.MemberDefinition.SetIsAssigned ();
                                } else {
-                                       FieldInfo fi = ((FieldExpr) member).FieldInfo;
+                                       var fi = ((FieldExpr) member).Spec;
 
-                                       if (fi.IsInitOnly) {
-                                               Error_InvalidNamedArgument (member_name);
+                                       if (fi.IsReadOnly || fi.IsStatic || !fi.IsPublic) {
+                                               Error_InvalidNamedArgument (ec, a);
                                                return false;
                                        }
 
                                        if (!IsValidArgumentType (member.Type)) {
-                                               Report.SymbolRelatedToPreviousError (fi);
-                                               Error_InvalidNamedAgrumentType (member_name);
+                                               ec.Report.SymbolRelatedToPreviousError (fi);
+                                               Error_InvalidNamedArgumentType (ec, a);
                                                return false;
                                        }
 
-                                       object value;
-                                       if (!a.Expr.GetAttributableValue (ec, member.Type, out value))
-                                               return false;
+                                       obsolete_attr = fi.GetAttributeObsolete ();
+                                       fi.MemberDefinition.SetIsAssigned ();
+                               }
 
-                                       FieldBase fb = TypeManager.GetField (fi);
-                                       if (fb != null)
-                                               obsolete_attr = fb.GetObsoleteAttribute ();
-                                       else
-                                               obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (fi);
+                               if (obsolete_attr != null && !context.IsObsolete)
+                                       AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location, Report);
 
-                                       field_values.Add (value);                                       
-                                       field_infos.Add (fi);
+                               if (a.Type != member.Type) {
+                                       a.Expr = Convert.ImplicitConversionRequired (ec, a.Expr, member.Type, a.Expr.Location);
                                }
 
-                               if (obsolete_attr != null && !Owner.ResolveContext.IsInObsoleteScope)
-                                       AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location);
+                               if (a.Expr != null)
+                                       named_values.Add (new KeyValuePair<MemberExpr, NamedArgument> ((MemberExpr) member, a));
                        }
 
-                       prop_info_arr = new PropertyInfo [prop_infos.Count];
-                       field_info_arr = new FieldInfo [field_infos.Count];
-                       field_values_arr = new object [field_values.Count];
-                       prop_values_arr = new object [prop_values.Count];
-
-                       field_infos.CopyTo  (field_info_arr, 0);
-                       field_values.CopyTo (field_values_arr, 0);
-
-                       prop_values.CopyTo  (prop_values_arr, 0);
-                       prop_infos.CopyTo   (prop_info_arr, 0);
-
                        return true;
                }
 
@@ -649,7 +589,7 @@ namespace Mono.CSharp {
                public string GetValidTargets ()
                {
                        StringBuilder sb = new StringBuilder ();
-                       AttributeTargets targets = GetAttributeUsage (Type).ValidOn;
+                       AttributeTargets targets = Type.GetAttributeUsage (context.Module.PredefinedAttributes.AttributeUsage).ValidOn;
 
                        if ((targets & AttributeTargets.Assembly) != 0)
                                sb.Append ("assembly, ");
@@ -693,51 +633,15 @@ namespace Mono.CSharp {
                        if ((targets & AttributeTargets.ReturnValue) != 0)
                                sb.Append ("return, ");
 
-#if NET_2_0
                        if ((targets & AttributeTargets.GenericParameter) != 0)
                                sb.Append ("type parameter, ");
-#endif                 
-                       return sb.Remove (sb.Length - 2, 2).ToString ();
-               }
-
-               /// <summary>
-               /// Returns AttributeUsage attribute based on types hierarchy
-               /// </summary>
-               static AttributeUsageAttribute GetAttributeUsage (Type type)
-               {
-                       AttributeUsageAttribute ua = usage_attr_cache [type] as AttributeUsageAttribute;
-                       if (ua != null)
-                               return ua;
-
-                       Class attr_class = TypeManager.LookupClass (type);
-
-                       if (attr_class == null) {
-                               object[] usage_attr = type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
-                               ua = (AttributeUsageAttribute)usage_attr [0];
-                               usage_attr_cache.Add (type, ua);
-                               return ua;
-                       }
-
-                       Attribute a = null;
-                       if (attr_class.OptAttributes != null)
-                               a = attr_class.OptAttributes.Search (TypeManager.attribute_usage_type);
-
-                       if (a == null) {
-                               if (attr_class.TypeBuilder.BaseType != TypeManager.attribute_type)
-                                       ua = GetAttributeUsage (attr_class.TypeBuilder.BaseType);
-                               else
-                                       ua = DefaultUsageAttribute;
-                       } else {
-                               ua = a.GetAttributeUsageAttribute ();
-                       }
 
-                       usage_attr_cache.Add (type, ua);
-                       return ua;
+                       return sb.Remove (sb.Length - 2, 2).ToString ();
                }
 
-               AttributeUsageAttribute GetAttributeUsageAttribute ()
+               public AttributeUsageAttribute GetAttributeUsageAttribute ()
                {
-                       if (pos_values == null)
+                       if (!arg_resolved)
                                // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
                                // But because a lot of attribute class code must be rewritten will be better to wait...
                                Resolve ();
@@ -745,15 +649,15 @@ namespace Mono.CSharp {
                        if (resolve_error)
                                return DefaultUsageAttribute;
 
-                       AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
+                       AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets) ((Constant) pos_args[0].Expr).GetValue ());
 
-                       object field = GetPropertyValue ("AllowMultiple");
+                       var field = GetNamedValue ("AllowMultiple") as BoolConstant;
                        if (field != null)
-                               usage_attribute.AllowMultiple = (bool)field;
+                               usage_attribute.AllowMultiple = field.Value;
 
-                       field = GetPropertyValue ("Inherited");
+                       field = GetNamedValue ("Inherited") as BoolConstant;
                        if (field != null)
-                               usage_attribute.Inherited = (bool)field;
+                               usage_attribute.Inherited = field.Value;
 
                        return usage_attribute;
                }
@@ -763,15 +667,15 @@ namespace Mono.CSharp {
                /// </summary>
                public string GetIndexerAttributeValue ()
                {
-                       if (pos_values == null)
+                       if (!arg_resolved)
                                // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
                                // But because a lot of attribute class code must be rewritten will be better to wait...
                                Resolve ();
 
-                       if (resolve_error)
+                       if (resolve_error || pos_args.Count != 1 || !(pos_args[0].Expr is Constant))
                                return null;
 
-                       return pos_values [0] as string;
+                       return ((Constant) pos_args[0].Expr).GetValue () as string;
                }
 
                /// <summary>
@@ -779,7 +683,7 @@ namespace Mono.CSharp {
                /// </summary>
                public string GetConditionalAttributeValue ()
                {
-                       if (pos_values == null)
+                       if (!arg_resolved)
                                // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
                                // But because a lot of attribute class code must be rewritten will be better to wait...
                                Resolve ();
@@ -787,7 +691,7 @@ namespace Mono.CSharp {
                        if (resolve_error)
                                return null;
 
-                       return (string)pos_values [0];
+                       return ((Constant) pos_args[0].Expr).GetValue () as string;
                }
 
                /// <summary>
@@ -795,21 +699,28 @@ namespace Mono.CSharp {
                /// </summary>
                public ObsoleteAttribute GetObsoleteAttribute ()
                {
-                       if (pos_values == null)
+                       if (!arg_resolved) {
+                               // corlib only case when obsolete is used before is resolved
+                               var c = Type.MemberDefinition as Class;
+                               if (c != null && !c.HasMembersDefined)
+                                       c.Define ();
+                               
                                // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
                                // But because a lot of attribute class code must be rewritten will be better to wait...
                                Resolve ();
+                       }
 
                        if (resolve_error)
                                return null;
 
-                       if (pos_values == null || pos_values.Length == 0)
+                       if (pos_args == null)
                                return new ObsoleteAttribute ();
 
-                       if (pos_values.Length == 1)
-                               return new ObsoleteAttribute ((string)pos_values [0]);
+                       string msg = ((Constant) pos_args[0].Expr).GetValue () as string;
+                       if (pos_args.Count == 1)
+                               return new ObsoleteAttribute (msg);
 
-                       return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
+                       return new ObsoleteAttribute (msg, ((BoolConstant) pos_args[1].Expr).Value);
                }
 
                /// <summary>
@@ -819,7 +730,7 @@ namespace Mono.CSharp {
                /// </summary>
                public bool GetClsCompliantAttributeValue ()
                {
-                       if (pos_values == null)
+                       if (!arg_resolved)
                                // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
                                // But because a lot of attribute class code must be rewritten will be better to wait...
                                Resolve ();
@@ -827,18 +738,18 @@ namespace Mono.CSharp {
                        if (resolve_error)
                                return false;
 
-                       return (bool)pos_values [0];
+                       return ((BoolConstant) pos_args[0].Expr).Value;
                }
 
-               public Type GetCoClassAttributeValue ()
+               public TypeSpec GetCoClassAttributeValue ()
                {
-                       if (pos_values == null)
+                       if (!arg_resolved)
                                Resolve ();
 
                        if (resolve_error)
                                return null;
 
-                       return (Type)pos_values [0];
+                       return GetArgumentType ();
                }
 
                public bool CheckTarget ()
@@ -850,13 +761,14 @@ namespace Mono.CSharp {
                        }
 
                        // TODO: we can skip the first item
-                       if (((IList) valid_targets).Contains (ExplicitTarget)) {
+                       if (Array.Exists (valid_targets, i => i == ExplicitTarget)) {
                                switch (ExplicitTarget) {
-                                       case "return": Target = AttributeTargets.ReturnValue; return true;
-                                       case "param": Target = AttributeTargets.Parameter; return true;
-                                       case "field": Target = AttributeTargets.Field; return true;
-                                       case "method": Target = AttributeTargets.Method; return true;
-                                       case "property": Target = AttributeTargets.Property; return true;
+                               case "return": Target = AttributeTargets.ReturnValue; return true;
+                               case "param": Target = AttributeTargets.Parameter; return true;
+                               case "field": Target = AttributeTargets.Field; return true;
+                               case "method": Target = AttributeTargets.Method; return true;
+                               case "property": Target = AttributeTargets.Property; return true;
+                               case "module": Target = AttributeTargets.Module; return true;
                                }
                                throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
                        }
@@ -867,19 +779,22 @@ namespace Mono.CSharp {
                                sb.Append (", ");
                        }
                        sb.Remove (sb.Length - 2, 2);
-                       Report.Error (657, Location, "`{0}' is not a valid attribute location for this declaration. " +
-                               "Valid attribute locations for this declaration are `{1}'", ExplicitTarget, sb.ToString ());
+                       Report.Warning (657, 1, Location,
+                               "`{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are `{1}'. All attributes in this section will be ignored",
+                               ExplicitTarget, sb.ToString ());
                        return false;
                }
 
                /// <summary>
                /// Tests permitted SecurityAction for assembly or other types
                /// </summary>
-               protected virtual bool IsSecurityActionValid (bool for_assembly)
+               bool IsSecurityActionValid ()
                {
                        SecurityAction action = GetSecurityActionValue ();
+                       bool for_assembly = Target == AttributeTargets.Assembly || Target == AttributeTargets.Module;
 
                        switch (action) {
+#pragma warning disable 618
                        case SecurityAction.Demand:
                        case SecurityAction.Assert:
                        case SecurityAction.Deny:
@@ -896,6 +811,7 @@ namespace Mono.CSharp {
                                if (for_assembly)
                                        return true;
                                break;
+#pragma warning restore 618
 
                        default:
                                Error_AttributeEmitError ("SecurityAction is out of range");
@@ -908,267 +824,114 @@ namespace Mono.CSharp {
 
                System.Security.Permissions.SecurityAction GetSecurityActionValue ()
                {
-                       return (SecurityAction)pos_values [0];
+                       return (SecurityAction) ((Constant) pos_args[0].Expr).GetValue ();
                }
 
                /// <summary>
                /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
                /// </summary>
                /// <returns></returns>
-               public void ExtractSecurityPermissionSet (ListDictionary permissions)
-               {
-                       Type orig_assembly_type = null;
-
-                       if (TypeManager.LookupDeclSpace (Type) != null) {
-                               if (!RootContext.StdLib) {
-                                       orig_assembly_type = Type.GetType (Type.FullName);
-                               } else {
-                                       string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
-                                       if (orig_version_path == null) {
-                                               Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
-                                               return;
-                                       }
-
-                                       if (orig_sec_assembly == null) {
-                                               string file = Path.Combine (orig_version_path, Driver.OutputFile);
-                                               orig_sec_assembly = Assembly.LoadFile (file);
-                                       }
-
-                                       orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
-                                       if (orig_assembly_type == null) {
-                                               Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' " +
-                                                               "was not found in previous version of assembly");
-                                               return;
-                                       }
-                               }
-                       }
-
-                       SecurityAttribute sa;
-                       // For all non-selfreferencing security attributes we can avoid all hacks
-                       if (orig_assembly_type == null) {
-                               sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
-
-                               if (prop_info_arr != null) {
-                                       for (int i = 0; i < prop_info_arr.Length; ++i) {
-                                               PropertyInfo pi = prop_info_arr [i];
-                                               pi.SetValue (sa, prop_values_arr [i], null);
-                                       }
-                               }
+               public void ExtractSecurityPermissionSet (MethodSpec ctor, ref SecurityType permissions)
+               {
+#if STATIC
+                       object[] values = new object[pos_args.Count];
+                       for (int i = 0; i < values.Length; ++i)
+                               values[i] = ((Constant) pos_args[i].Expr).GetValue ();
+
+                       PropertyInfo[] prop;
+                       object[] prop_values;
+                       if (named_values == null) {
+                               prop = null;
+                               prop_values = null;
                        } else {
-                               // HACK: All security attributes have same ctor syntax
-                               sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
-
-                               // All types are from newly created assembly but for invocation with old one we need to convert them
-                               if (prop_info_arr != null) {
-                                       for (int i = 0; i < prop_info_arr.Length; ++i) {
-                                               PropertyInfo emited_pi = prop_info_arr [i];
-                                               // FIXME: We are missing return type filter
-                                               // TODO: pi can be null
-                                               PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name);
-
-                                               object old_instance = pi.PropertyType.IsEnum ?
-                                                       System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
-                                                       prop_values_arr [i];
-
-                                               pi.SetValue (sa, old_instance, null);
-                                       }
-                               }
-                       }
-
-                       IPermission perm;
-                       perm = sa.CreatePermission ();
-                       SecurityAction action = GetSecurityActionValue ();
-
-                       // IS is correct because for corlib we are using an instance from old corlib
-                       if (!(perm is System.Security.CodeAccessPermission)) {
-                               switch (action) {
-                                       case SecurityAction.Demand:
-                                               action = (SecurityAction)13;
-                                               break;
-                                       case SecurityAction.LinkDemand:
-                                               action = (SecurityAction)14;
-                                               break;
-                                       case SecurityAction.InheritanceDemand:
-                                               action = (SecurityAction)15;
-                                               break;
+                               prop = new PropertyInfo[named_values.Count];
+                               prop_values = new object [named_values.Count];
+                               for (int i = 0; i < prop.Length; ++i) {
+                                       prop [i] = ((PropertyExpr) named_values [i].Key).PropertyInfo.MetaInfo;
+                                       prop_values [i] = ((Constant) named_values [i].Value.Expr).GetValue ();
                                }
                        }
 
-                       PermissionSet ps = (PermissionSet)permissions [action];
-                       if (ps == null) {
-                               if (sa is PermissionSetAttribute)
-                                       ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
-                               else
-                                       ps = new PermissionSet (PermissionState.None);
+                       if (permissions == null)
+                               permissions = new SecurityType ();
 
-                               permissions.Add (action, ps);
-                       } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
-                               ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
-                               permissions [action] = ps;
-                       }
-                       ps.AddPermission (perm);
+                       var cab = new CustomAttributeBuilder ((ConstructorInfo) ctor.GetMetaInfo (), values, prop, prop_values);
+                       permissions.Add (cab);
+#else
+                       throw new NotSupportedException ();
+#endif
                }
 
-               public object GetPropertyValue (string name)
+               public Constant GetNamedValue (string name)
                {
-                       if (prop_info_arr == null)
+                       if (named_values == null)
                                return null;
 
-                       for (int i = 0; i < prop_info_arr.Length; ++i) {
-                               if (prop_info_arr [i].Name == name)
-                                       return prop_values_arr [i];
+                       for (int i = 0; i < named_values.Count; ++i) {
+                               if (named_values [i].Value.Name == name)
+                                       return named_values [i].Value.Expr as Constant;
                        }
 
                        return null;
                }
 
-               //
-               // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
-               // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
-               // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
-               //
-#if !NET_2_0
-               public UnmanagedMarshal GetMarshal (Attributable attr)
+               public CharSet GetCharSetValue ()
                {
-                       UnmanagedType UnmanagedType;
-                       if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
-                               UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
-                       else
-                               UnmanagedType = (UnmanagedType) pos_values [0];
-
-                       object value = GetFieldValue ("SizeParamIndex");
-                       if (value != null && UnmanagedType != UnmanagedType.LPArray) {
-                               Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
-                               return null;
-                       }
+                       return (CharSet) System.Enum.Parse (typeof (CharSet), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
+               }
 
-                       object o = GetFieldValue ("ArraySubType");
-                       UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
+               public bool HasField (string fieldName)
+               {
+                       if (named_values == null)
+                               return false;
 
-                       switch (UnmanagedType) {
-                       case UnmanagedType.CustomMarshaler: {
-                               MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
-                                       BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
-                               if (define_custom == null) {
-                                       Report.RuntimeMissingSupport (Location, "set marshal info");
-                                       return null;
-                               }
-                               
-                               object [] args = new object [4];
-                               args [0] = GetFieldValue ("MarshalTypeRef");
-                               args [1] = GetFieldValue ("MarshalCookie");
-                               args [2] = GetFieldValue ("MarshalType");
-                               args [3] = Guid.Empty;
-                               return (UnmanagedMarshal) define_custom.Invoke (null, args);
-                       }
-                       case UnmanagedType.LPArray: {
-                               object size_const = GetFieldValue ("SizeConst");
-                               object size_param_index = GetFieldValue ("SizeParamIndex");
-
-                               if ((size_const != null) || (size_param_index != null)) {
-                                       MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
-                                               BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
-                                       if (define_array == null) {
-                                               Report.RuntimeMissingSupport (Location, "set marshal info");
-                                               return null;
-                                       }
-                               
-                                       object [] args = new object [3];
-                                       args [0] = array_sub_type;
-                                       args [1] = size_const == null ? -1 : size_const;
-                                       args [2] = size_param_index == null ? -1 : size_param_index;
-                                       return (UnmanagedMarshal) define_array.Invoke (null, args);
-                               }
-                               else
-                                       return UnmanagedMarshal.DefineLPArray (array_sub_type);
+                       foreach (var na in named_values) {
+                               if (na.Value.Name == fieldName)
+                                       return true;
                        }
-                       case UnmanagedType.SafeArray:
-                               return UnmanagedMarshal.DefineSafeArray (array_sub_type);
 
-                       case UnmanagedType.ByValArray:
-                               FieldBase fm = attr as FieldBase;
-                               if (fm == null) {
-                                       Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
-                                       return null;
-                               }
-                               return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
-
-                       case UnmanagedType.ByValTStr:
-                               return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
+                       return false;
+               }
 
-                       default:
-                               return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
-                       }
+               //
+               // Returns true for MethodImplAttribute with MethodImplOptions.InternalCall value
+               // 
+               public bool IsInternalCall ()
+               {
+                       return (GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0;
                }
 
-               object GetFieldValue (string name)
+               public MethodImplOptions GetMethodImplOptions ()
                {
-                       int i;
-                       if (field_info_arr == null)
-                               return null;
-                       i = 0;
-                       foreach (FieldInfo fi in field_info_arr) {
-                               if (fi.Name == name)
-                                       return GetValue (field_values_arr [i]);
-                               i++;
+                       MethodImplOptions options = 0;
+                       if (pos_args.Count == 1) {
+                               options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
+                       } else if (HasField ("Value")) {
+                               var named = GetNamedValue ("Value");
+                               options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), named.GetValue ().ToString ());
                        }
-                       return null;
+
+                       return options;
                }
 
-               static object GetValue (object value)
+               //
+               // Returns true for StructLayoutAttribute with LayoutKind.Explicit value
+               // 
+               public bool IsExplicitLayoutKind ()
                {
-                       if (value is EnumConstant)
-                               return ((EnumConstant) value).GetValue ();
-                       else
-                               return value;                           
+                       if (pos_args == null || pos_args.Count != 1)
+                               return false;
+
+                       var value = (LayoutKind) System.Enum.Parse (typeof (LayoutKind), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
+                       return value == LayoutKind.Explicit;
                }
-               
-#endif
 
-               public CharSet GetCharSetValue ()
-               {
-                       return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
-               }
-
-               public bool HasField (string fieldName)
+               public Expression GetParameterDefaultValue ()
                {
-                       if (field_info_arr == null)
-                               return false;
-
-                       foreach (FieldInfo fi in field_info_arr) {
-                               if (fi.Name == fieldName)
-                                       return true;
-                       }
-
-                       return false;
-               }
-
-               public bool IsInternalMethodImplAttribute {
-                       get {
-                               if (Type != TypeManager.methodimpl_attr_type)
-                                       return false;
-
-                               MethodImplOptions options;
-                               if (pos_values[0].GetType () != typeof (MethodImplOptions))
-                                       options = (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values[0]);
-                               else
-                                       options = (MethodImplOptions)pos_values[0];
-
-                               return (options & MethodImplOptions.InternalCall) != 0;
-                       }
-               }
-
-               public LayoutKind GetLayoutKindValue ()
-               {
-                       if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
-                               return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
-
-                       return (LayoutKind)pos_values [0];
-               }
+                       if (pos_args == null)
+                               return null;
 
-               public object GetParameterDefaultValue ()
-               {
-                       return pos_values [0];
+                       return pos_args[0].Expr;
                }
 
                public override bool Equals (object obj)
@@ -1182,19 +945,21 @@ namespace Mono.CSharp {
 
                public override int GetHashCode ()
                {
-                       return base.GetHashCode ();
+                       return Type.GetHashCode () ^ Target.GetHashCode ();
                }
 
                /// <summary>
                /// Emit attribute for Attributable symbol
                /// </summary>
-               public void Emit (ListDictionary allEmitted)
+               public void Emit (Dictionary<Attribute, List<Attribute>> allEmitted)
                {
-                       CustomAttributeBuilder cb = Resolve ();
-                       if (cb == null)
+                       var ctor = Resolve ();
+                       if (ctor == null)
                                return;
 
-                       AttributeUsageAttribute usage_attr = GetAttributeUsage (Type);
+                       var predefined = context.Module.PredefinedAttributes;
+
+                       AttributeUsageAttribute usage_attr = Type.GetAttributeUsage (predefined.AttributeUsage);
                        if ((usage_attr.ValidOn & Target) == 0) {
                                Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
                                              "It is valid on `{1}' declarations only",
@@ -1202,20 +967,98 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       try {
-                               foreach (Attributable owner in owners)
-                                       owner.ApplyAttributeBuilder (this, cb);
+                       byte[] cdata;
+                       if (pos_args == null && named_values == null) {
+                               cdata = AttributeEncoder.Empty;
+                       } else {
+                               AttributeEncoder encoder = new AttributeEncoder ();
+
+                               if (pos_args != null) {
+                                       var param_types = ctor.Parameters.Types;
+                                       for (int j = 0; j < pos_args.Count; ++j) {
+                                               var pt = param_types[j];
+                                               var arg_expr = pos_args[j].Expr;
+                                               if (j == 0) {
+                                                       if ((Type == predefined.IndexerName || Type == predefined.Conditional) && arg_expr is Constant) {
+                                                               string v = ((Constant) arg_expr).GetValue () as string;
+                                                               if (!Tokenizer.IsValidIdentifier (v) || (Type == predefined.IndexerName && Tokenizer.IsKeyword (v))) {
+                                                                       context.Module.Compiler.Report.Error (633, arg_expr.Location,
+                                                                               "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
+                                                                       return;
+                                                               }
+                                                       } else if (Type == predefined.Guid) {
+                                                               try {
+                                                                       string v = ((StringConstant) arg_expr).Value;
+                                                                       new Guid (v);
+                                                               } catch (Exception e) {
+                                                                       Error_AttributeEmitError (e.Message);
+                                                                       return;
+                                                               }
+                                                       } else if (Type == predefined.AttributeUsage) {
+                                                               int v = ((IntConstant) ((EnumConstant) arg_expr).Child).Value;
+                                                               if (v == 0) {
+                                                                       context.Module.Compiler.Report.Error (591, Location, "Invalid value for argument to `{0}' attribute",
+                                                                               "System.AttributeUsage");
+                                                               }
+                                                       } else if (Type == predefined.MarshalAs) {
+                                                               if (pos_args.Count == 1) {
+                                                                       var u_type = (UnmanagedType) System.Enum.Parse (typeof (UnmanagedType), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
+                                                                       if (u_type == UnmanagedType.ByValArray && !(Owner is FieldBase)) {
+                                                                               Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
+                                                                       }
+                                                               }
+                                                       } else if (Type == predefined.DllImport) {
+                                                               if (pos_args.Count == 1 && pos_args[0].Expr is Constant) {
+                                                                       var value = ((Constant) pos_args[0].Expr).GetValue () as string;
+                                                                       if (string.IsNullOrEmpty (value))
+                                                                               Error_AttributeEmitError ("DllName cannot be empty");
+                                                               }
+                                                       } else if (Type == predefined.MethodImpl && pt.BuiltinType == BuiltinTypeSpec.Type.Short &&
+                                                               !System.Enum.IsDefined (typeof (MethodImplOptions), ((Constant) arg_expr).GetValue ().ToString ())) {
+                                                               Error_AttributeEmitError ("Incorrect argument value.");
+                                                               return;
+                                                       }
+                                               }
+
+                                               arg_expr.EncodeAttributeValue (context, encoder, pt);
+                                       }
+                               }
+
+                               if (named_values != null) {
+                                       encoder.Encode ((ushort) named_values.Count);
+                                       foreach (var na in named_values) {
+                                               if (na.Key is FieldExpr)
+                                                       encoder.Encode ((byte) 0x53);
+                                               else
+                                                       encoder.Encode ((byte) 0x54);
+
+                                               encoder.Encode (na.Key.Type);
+                                               encoder.Encode (na.Value.Name);
+                                               na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type);
+                                       }
+                               } else {
+                                       encoder.EncodeEmptyNamedArguments ();
+                               }
+
+                               cdata = encoder.ToArray ();
                        }
-                       catch (Exception e) {
+
+                       try {
+                               foreach (Attributable target in targets)
+                                       target.ApplyAttributeBuilder (this, ctor, cdata, predefined);
+                       } catch (Exception e) {
+                               if (e is BadImageFormat && Report.Errors > 0)
+                                       return;
+
                                Error_AttributeEmitError (e.Message);
                                return;
                        }
 
                        if (!usage_attr.AllowMultiple && allEmitted != null) {
-                               if (allEmitted.Contains (this)) {
-                                       ArrayList a = allEmitted [this] as ArrayList;
+                               if (allEmitted.ContainsKey (this)) {
+                                       var a = allEmitted [this];
                                        if (a == null) {
-                                               a = new ArrayList (2);
+                                               a = new List<Attribute> (2);
                                                allEmitted [this] = a;
                                        }
                                        a.Add (this);
@@ -1224,48 +1067,27 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       if (!RootContext.VerifyClsCompliance)
+                       if (!context.Module.Compiler.Settings.VerifyClsCompliance)
                                return;
 
                        // Here we are testing attribute arguments for array usage (error 3016)
                        if (Owner.IsClsComplianceRequired ()) {
-                               if (PosArguments != null) {
-                                       foreach (Argument arg in PosArguments) { 
-                                               // Type is undefined (was error 246)
-                                               if (arg.Type == null)
-                                                       return;
-
-                                               if (arg.Type.IsArray) {
-                                                       Report.Warning (3016, 1, Location, "Arrays as attribute arguments are not CLS-compliant");
-                                                       return;
-                                               }
-                                       }
-                               }
+                               if (pos_args != null)
+                                       pos_args.CheckArrayAsAttribute (context.Module.Compiler);
                        
                                if (NamedArguments == null)
                                        return;
-                       
-                               foreach (DictionaryEntry de in NamedArguments) {
-                                       Argument arg  = (Argument) de.Value;
 
-                                       // Type is undefined (was error 246)
-                                       if (arg.Type == null)
-                                               return;
-
-                                       if (arg.Type.IsArray) {
-                                               Report.Warning (3016, 1, Location, "Arrays as attribute arguments are not CLS-compliant");
-                                               return;
-                                       }
-                               }
+                               NamedArguments.CheckArrayAsAttribute (context.Module.Compiler);
                        }
                }
 
                private Expression GetValue () 
                {
-                       if (PosArguments == null || PosArguments.Count < 1)
+                       if (pos_args == null || pos_args.Count < 1)
                                return null;
 
-                       return ((Argument) PosArguments [0]).Expr;
+                       return pos_args[0].Expr;
                }
 
                public string GetString () 
@@ -1284,147 +1106,49 @@ namespace Mono.CSharp {
                        return false;
                }
 
-               public Type GetArgumentType ()
+               public TypeSpec GetArgumentType ()
                {
                        TypeOf e = GetValue () as TypeOf;
                        if (e == null)
                                return null;
                        return e.TypeArgument;
                }
-
-               public override Expression CreateExpressionTree (EmitContext ec)
-               {
-                       throw new NotSupportedException ("ET");
-               }
-
-               public override Expression DoResolve (EmitContext ec)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override void Emit (EmitContext ec)
-               {
-                       throw new NotImplementedException ();
-               }
        }
        
-
-       /// <summary>
-       /// For global attributes (assembly, module) we need special handling.
-       /// Attributes can be located in the several files
-       /// </summary>
-       public class GlobalAttribute : Attribute
+       public class Attributes
        {
-               public readonly NamespaceEntry ns;
-
-               public GlobalAttribute (NamespaceEntry ns, string target, 
-                                       Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped):
-                       base (target, left_expr, identifier, args, loc, nameEscaped)
-               {
-                       this.ns = ns;
-                       this.owners = new Attributable[1];
-               }
-               
-               public override void AttachTo (Attributable owner)
-               {
-                       if (ExplicitTarget == "assembly") {
-                               owners [0] = CodeGen.Assembly;
-                               return;
-                       }
-                       if (ExplicitTarget == "module") {
-                               owners [0] = CodeGen.Module;
-                               return;
-                       }
-                       throw new NotImplementedException ("Unknown global explicit target " + ExplicitTarget);
-               }
-
-               void Enter ()
-               {
-                       // RootContext.ToplevelTypes has a single NamespaceEntry which gets overwritten
-                       // each time a new file is parsed.  However, we need to use the NamespaceEntry
-                       // in effect where the attribute was used.  Since code elsewhere cannot assume
-                       // that the NamespaceEntry is right, just overwrite it.
-                       //
-                       // Precondition: RootContext.ToplevelTypes == null
-
-                       if (RootContext.ToplevelTypes.NamespaceEntry != null)
-                               throw new InternalErrorException (Location + " non-null NamespaceEntry");
-
-                       RootContext.ToplevelTypes.NamespaceEntry = ns;
-               }
-
-               protected override bool IsSecurityActionValid (bool for_assembly)
-               {
-                       return base.IsSecurityActionValid (true);
-               }
-
-               void Leave ()
-               {
-                       RootContext.ToplevelTypes.NamespaceEntry = null;
-               }
-
-               protected override TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
-               {
-                       try {
-                               Enter ();
-                               return base.ResolveAsTypeTerminal (expr, ec, silent);
-                       }
-                       finally {
-                               Leave ();
-                       }
-               }
-
-               protected override ConstructorInfo ResolveConstructor (EmitContext ec)
-               {
-                       try {
-                               Enter ();
-                               return base.ResolveConstructor (ec);
-                       }
-                       finally {
-                               Leave ();
-                       }
-               }
-
-               protected override bool ResolveNamedArguments (EmitContext ec)
-               {
-                       try {
-                               Enter ();
-                               return base.ResolveNamedArguments (ec);
-                       }
-                       finally {
-                               Leave ();
-                       }
-               }
-       }
-
-       public class Attributes {
-               public readonly ArrayList Attrs;
+               public readonly List<Attribute> Attrs;
 
                public Attributes (Attribute a)
                {
-                       Attrs = new ArrayList ();
+                       Attrs = new List<Attribute> ();
                        Attrs.Add (a);
                }
 
-               public Attributes (ArrayList attrs)
+               public Attributes (List<Attribute> attrs)
                {
                        Attrs = attrs;
                }
 
-               public void AddAttributes (ArrayList attrs)
+               public void AddAttribute (Attribute attr)
+               {
+                       Attrs.Add (attr);
+               }
+
+               public void AddAttributes (List<Attribute> attrs)
                {
                        Attrs.AddRange (attrs);
                }
 
-               public void AttachTo (Attributable attributable)
+               public void AttachTo (Attributable attributable, IMemberContext context)
                {
                        foreach (Attribute a in Attrs)
-                               a.AttachTo (attributable);
+                               a.AttachTo (attributable, context);
                }
 
                public Attributes Clone ()
                {
-                       ArrayList al = new ArrayList (Attrs.Count);
+                       var al = new List<Attribute> (Attrs.Count);
                        foreach (Attribute a in Attrs)
                                al.Add (a.Clone ());
 
@@ -1436,16 +1160,50 @@ namespace Mono.CSharp {
                /// </summary>
                public bool CheckTargets ()
                {
-                       foreach (Attribute a in Attrs) {
-                               if (!a.CheckTarget ())
-                                       return false;
+                       for (int i = 0; i < Attrs.Count; ++i) {
+                               if (!Attrs [i].CheckTarget ())
+                                       Attrs.RemoveAt (i--);
                        }
+
                        return true;
                }
 
-               public Attribute Search (Type t)
+               public void ConvertGlobalAttributes (TypeContainer member, NamespaceContainer currentNamespace, bool isGlobal)
+               {
+                       var member_explicit_targets = member.ValidAttributeTargets;
+                       for (int i = 0; i < Attrs.Count; ++i) {
+                               var attr = Attrs[0];
+                               if (attr.ExplicitTarget == null)
+                                       continue;
+
+                               int ii;
+                               for (ii = 0; ii < member_explicit_targets.Length; ++ii) {
+                                       if (attr.ExplicitTarget == member_explicit_targets[ii]) {
+                                               ii = -1;
+                                               break;
+                                       }
+                               }
+
+                               if (ii < 0 || !isGlobal)
+                                       continue;
+
+                               member.Module.AddAttribute (attr, currentNamespace);
+                               Attrs.RemoveAt (i);
+                               --i;
+                       }
+               }
+
+               public Attribute Search (PredefinedAttribute t)
+               {
+                       return Search (null, t);
+               }
+
+               public Attribute Search (string explicitTarget, PredefinedAttribute t)
                {
                        foreach (Attribute a in Attrs) {
+                               if (explicitTarget != null && a.ExplicitTarget != explicitTarget)
+                                       continue;
+
                                if (a.ResolveType () == t)
                                        return a;
                        }
@@ -1455,26 +1213,26 @@ namespace Mono.CSharp {
                /// <summary>
                /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
                /// </summary>
-               public Attribute[] SearchMulti (Type t)
+               public Attribute[] SearchMulti (PredefinedAttribute t)
                {
-                       ArrayList ar = null;
+                       List<Attribute> ar = null;
 
                        foreach (Attribute a in Attrs) {
                                if (a.ResolveType () == t) {
                                        if (ar == null)
-                                               ar = new ArrayList ();
+                                               ar = new List<Attribute> (Attrs.Count);
                                        ar.Add (a);
                                }
                        }
 
-                       return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
+                       return ar == null ? null : ar.ToArray ();
                }
 
                public void Emit ()
                {
                        CheckTargets ();
 
-                       ListDictionary ld = Attrs.Count > 1 ? new ListDictionary () : null;
+                       Dictionary<Attribute, List<Attribute>> ld = Attrs.Count > 1 ? new Dictionary<Attribute, List<Attribute>> () : null;
 
                        foreach (Attribute a in Attrs)
                                a.Emit (ld);
@@ -1482,407 +1240,731 @@ namespace Mono.CSharp {
                        if (ld == null || ld.Count == 0)
                                return;
 
-                       foreach (DictionaryEntry d in ld) {
+                       foreach (var d in ld) {
                                if (d.Value == null)
                                        continue;
 
-                               foreach (Attribute collision in (ArrayList)d.Value)
-                                       Report.SymbolRelatedToPreviousError (collision.Location, "");
+                               Attribute a = d.Key;
 
-                               Attribute a = (Attribute)d.Key;
-                               Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
+                               foreach (Attribute collision in d.Value)
+                                       a.Report.SymbolRelatedToPreviousError (collision.Location, "");
+
+                               a.Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
                                        a.GetSignatureForError ());
                        }
                }
 
-               public bool Contains (Type t)
+               public bool Contains (PredefinedAttribute t)
                {
                        return Search (t) != null;
                }
        }
 
-       /// <summary>
-       /// Helper class for attribute verification routine.
-       /// </summary>
-       sealed class AttributeTester
+       public sealed class AttributeEncoder
        {
-               static PtrHashtable analyzed_types;
-               static PtrHashtable analyzed_types_obsolete;
-               static PtrHashtable analyzed_member_obsolete;
-               static PtrHashtable analyzed_method_excluded;
-               static PtrHashtable fixed_buffer_cache;
+               [Flags]
+               public enum EncodedTypeProperties
+               {
+                       None = 0,
+                       DynamicType = 1,
+                       TypeParameter = 1 << 1
+               }
 
-               static object TRUE = new object ();
-               static object FALSE = new object ();
+               public static readonly byte[] Empty;
 
-               static AttributeTester ()
+               byte[] buffer;
+               int pos;
+               const ushort Version = 1;
+
+               static AttributeEncoder ()
                {
-                       Reset ();
+                       Empty = new byte[4];
+                       Empty[0] = (byte) Version;
                }
 
-               private AttributeTester ()
+               public AttributeEncoder ()
                {
+                       buffer = new byte[32];
+                       Encode (Version);
                }
 
-               public static void Reset ()
+               public void Encode (bool value)
                {
-                       analyzed_types = new PtrHashtable ();
-                       analyzed_types_obsolete = new PtrHashtable ();
-                       analyzed_member_obsolete = new PtrHashtable ();
-                       analyzed_method_excluded = new PtrHashtable ();
-                       fixed_buffer_cache = new PtrHashtable ();
+                       Encode (value ? (byte) 1 : (byte) 0);
                }
 
-               public enum Result {
-                       Ok,
-                       RefOutArrayError,
-                       ArrayArrayError
+               public void Encode (byte value)
+               {
+                       if (pos == buffer.Length)
+                               Grow (1);
+
+                       buffer [pos++] = value;
                }
 
-               /// <summary>
-               /// Returns true if parameters of two compared methods are CLS-Compliant.
-               /// It tests differing only in ref or out, or in array rank.
-               /// </summary>
-               public static Result AreOverloadedMethodParamsClsCompliant (AParametersCollection pa, AParametersCollection pb) 
-               {
-                       Type [] types_a = pa.Types;
-                       Type [] types_b = pb.Types;
-                       if (types_a == null || types_b == null)
-                               return Result.Ok;
-
-                       if (types_a.Length != types_b.Length)
-                               return Result.Ok;
-
-                       Result result = Result.Ok;
-                       for (int i = 0; i < types_b.Length; ++i) {
-                               Type aType = types_a [i];
-                               Type bType = types_b [i];
-
-                               if (aType.IsArray && bType.IsArray) {
-                                       Type a_el_type = aType.GetElementType ();
-                                       Type b_el_type = bType.GetElementType ();
-                                       if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
-                                               result = Result.RefOutArrayError;
-                                               continue;
-                                       }
+               public void Encode (sbyte value)
+               {
+                       Encode ((byte) value);
+               }
 
-                                       if (a_el_type.IsArray || b_el_type.IsArray) {
-                                               result = Result.ArrayArrayError;
-                                               continue;
-                                       }
-                               }
+               public void Encode (short value)
+               {
+                       if (pos + 2 > buffer.Length)
+                               Grow (2);
 
-                               if (aType != bType)
-                                       return Result.Ok;
+                       buffer[pos++] = (byte) value;
+                       buffer[pos++] = (byte) (value >> 8);
+               }
 
-                               if (pa.FixedParameters [i].ModFlags != pb.FixedParameters [i].ModFlags)
-                                       result = Result.RefOutArrayError;
-                       }
-                       return result;
+               public void Encode (ushort value)
+               {
+                       Encode ((short) value);
                }
 
-               /// <summary>
-               /// This method tests the CLS compliance of external types. It doesn't test type visibility.
-               /// </summary>
-               public static bool IsClsCompliant (Type type) 
+               public void Encode (int value)
                {
-                       if (type == null)
-                               return true;
+                       if (pos + 4 > buffer.Length)
+                               Grow (4);
 
-                       object type_compliance = analyzed_types[type];
-                       if (type_compliance != null)
-                               return type_compliance == TRUE;
+                       buffer[pos++] = (byte) value;
+                       buffer[pos++] = (byte) (value >> 8);
+                       buffer[pos++] = (byte) (value >> 16);
+                       buffer[pos++] = (byte) (value >> 24);
+               }
 
-                       if (type.IsPointer) {
-                               analyzed_types.Add (type, FALSE);
-                               return false;
-                       }
+               public void Encode (uint value)
+               {
+                       Encode ((int) value);
+               }
 
-                       bool result;
-                       if (type.IsArray) {
-                               result = IsClsCompliant (TypeManager.GetElementType (type));
-                       } else if (TypeManager.IsNullableType (type)) {
-                               result = IsClsCompliant (TypeManager.GetTypeArguments (type) [0]);
-                       } else {
-                               result = AnalyzeTypeCompliance (type);
-                       }
-                       analyzed_types.Add (type, result ? TRUE : FALSE);
-                       return result;
-               }        
-        
-               /// <summary>
-               /// Returns IFixedBuffer implementation if field is fixed buffer else null.
-               /// </summary>
-               public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
+               public void Encode (long value)
                {
-                       // Fixed buffer helper type is generated as value type
-                       if (!fi.FieldType.IsValueType)
-                               return null;
+                       if (pos + 8 > buffer.Length)
+                               Grow (8);
 
-                       FieldBase fb = TypeManager.GetField (fi);
-                       if (fb != null) {
-                               return fb as IFixedBuffer;
-                       }
-                       
-                       if (TypeManager.GetConstant (fi) != null)
-                               return null;
+                       buffer[pos++] = (byte) value;
+                       buffer[pos++] = (byte) (value >> 8);
+                       buffer[pos++] = (byte) (value >> 16);
+                       buffer[pos++] = (byte) (value >> 24);
+                       buffer[pos++] = (byte) (value >> 32);
+                       buffer[pos++] = (byte) (value >> 40);
+                       buffer[pos++] = (byte) (value >> 48);
+                       buffer[pos++] = (byte) (value >> 56);
+               }
 
-                       object o = fixed_buffer_cache [fi];
-                       if (o == null) {
-                               if (TypeManager.fixed_buffer_attr_type == null)
-                                       return null;
+               public void Encode (ulong value)
+               {
+                       Encode ((long) value);
+               }
 
-                               if (!fi.IsDefined (TypeManager.fixed_buffer_attr_type, false)) {
-                                       fixed_buffer_cache.Add (fi, FALSE);
-                                       return null;
-                               }
-                               
-                               IFixedBuffer iff = new FixedFieldExternal (fi);
-                               fixed_buffer_cache.Add (fi, iff);
-                               return iff;
+               public void Encode (float value)
+               {
+                       Encode (SingleConverter.SingleToInt32Bits (value));
+               }
+
+               public void Encode (double value)
+               {
+                       Encode (BitConverter.DoubleToInt64Bits (value));
+               }
+
+               public void Encode (string value)
+               {
+                       if (value == null) {
+                               Encode ((byte) 0xFF);
+                               return;
                        }
 
-                       if (o == FALSE)
-                               return null;
+                       var buf = Encoding.UTF8.GetBytes(value);
+                       WriteCompressedValue (buf.Length);
+
+                       if (pos + buf.Length > buffer.Length)
+                               Grow (buf.Length);
 
-                       return (IFixedBuffer)o;
+                       Buffer.BlockCopy (buf, 0, buffer, pos, buf.Length);
+                       pos += buf.Length;
                }
 
-               public static void VerifyModulesClsCompliance ()
+               public EncodedTypeProperties Encode (TypeSpec type)
                {
-                       Module[] modules = RootNamespace.Global.Modules;
-                       if (modules == null)
-                               return;
+                       switch (type.BuiltinType) {
+                       case BuiltinTypeSpec.Type.Bool:
+                               Encode ((byte) 0x02);
+                               break;
+                       case BuiltinTypeSpec.Type.Char:
+                               Encode ((byte) 0x03);
+                               break;
+                       case BuiltinTypeSpec.Type.SByte:
+                               Encode ((byte) 0x04);
+                               break;
+                       case BuiltinTypeSpec.Type.Byte:
+                               Encode ((byte) 0x05);
+                               break;
+                       case BuiltinTypeSpec.Type.Short:
+                               Encode ((byte) 0x06);
+                               break;
+                       case BuiltinTypeSpec.Type.UShort:
+                               Encode ((byte) 0x07);
+                               break;
+                       case BuiltinTypeSpec.Type.Int:
+                               Encode ((byte) 0x08);
+                               break;
+                       case BuiltinTypeSpec.Type.UInt:
+                               Encode ((byte) 0x09);
+                               break;
+                       case BuiltinTypeSpec.Type.Long:
+                               Encode ((byte) 0x0A);
+                               break;
+                       case BuiltinTypeSpec.Type.ULong:
+                               Encode ((byte) 0x0B);
+                               break;
+                       case BuiltinTypeSpec.Type.Float:
+                               Encode ((byte) 0x0C);
+                               break;
+                       case BuiltinTypeSpec.Type.Double:
+                               Encode ((byte) 0x0D);
+                               break;
+                       case BuiltinTypeSpec.Type.String:
+                               Encode ((byte) 0x0E);
+                               break;
+                       case BuiltinTypeSpec.Type.Type:
+                               Encode ((byte) 0x50);
+                               break;
+                       case BuiltinTypeSpec.Type.Object:
+                               Encode ((byte) 0x51);
+                               break;
+                       case BuiltinTypeSpec.Type.Dynamic:
+                               Encode ((byte) 0x51);
+                               return EncodedTypeProperties.DynamicType;
+                       default:
+                               if (type.IsArray) {
+                                       Encode ((byte) 0x1D);
+                                       return Encode (TypeManager.GetElementType (type));
+                               }
 
-                       // The first module is generated assembly
-                       for (int i = 1; i < modules.Length; ++i) {
-                               Module module = modules [i];
-                               if (!GetClsCompliantAttributeValue (module, null)) {
-                                       Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
-                                                     "to match the assembly", module.Name);
-                                       return;
+                               if (type.Kind == MemberKind.Enum) {
+                                       Encode ((byte) 0x55);
+                                       EncodeTypeName (type);
                                }
+
+                               break;
                        }
+
+                       return EncodedTypeProperties.None;
                }
 
-               public static Type GetImportedIgnoreCaseClsType (string name)
+               public void EncodeTypeName (TypeSpec type)
                {
-                       foreach (Assembly a in RootNamespace.Global.Assemblies) {
-                               Type t = a.GetType (name, false, true);
-                               if (t == null)
-                                       continue;
+                       var old_type = type.GetMetaInfo ();
+                       Encode (type.MemberDefinition.IsImported ? old_type.AssemblyQualifiedName : old_type.FullName);
+               }
 
-                               if (IsClsCompliant (t))
-                                       return t;
-                       }
-                       return null;
+               //
+               // Encodes single property named argument per call
+               //
+               public void EncodeNamedPropertyArgument (PropertySpec property, Constant value)
+               {
+                       Encode ((ushort) 1);    // length
+                       Encode ((byte) 0x54); // property
+                       Encode (property.MemberType);
+                       Encode (property.Name);
+                       value.EncodeAttributeValue (null, this, property.MemberType);
                }
 
-               static bool GetClsCompliantAttributeValue (ICustomAttributeProvider attribute_provider, Assembly a) 
+               //
+               // Encodes single field named argument per call
+               //
+               public void EncodeNamedFieldArgument (FieldSpec field, Constant value)
                {
-                       if (TypeManager.cls_compliant_attribute_type == null)
-                               return false;
+                       Encode ((ushort) 1);    // length
+                       Encode ((byte) 0x53); // field
+                       Encode (field.MemberType);
+                       Encode (field.Name);
+                       value.EncodeAttributeValue (null, this, field.MemberType);
+               }
 
-                       object[] cls_attr = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
-                       if (cls_attr.Length == 0) {
-                               if (a == null)
-                                       return false;
+               public void EncodeNamedArguments<T> (T[] members, Constant[] values) where T : MemberSpec, IInterfaceMemberSpec
+               {
+                       Encode ((ushort) members.Length);
+
+                       for (int i = 0; i < members.Length; ++i)
+                       {
+                               var member = members[i];
+
+                               if (member.Kind == MemberKind.Field)
+                                       Encode ((byte) 0x53);
+                               else if (member.Kind == MemberKind.Property)
+                                       Encode ((byte) 0x54);
+                               else
+                                       throw new NotImplementedException (member.Kind.ToString ());
 
-                               return GetClsCompliantAttributeValue (a, null);
+                               Encode (member.MemberType);
+                               Encode (member.Name);
+                               values [i].EncodeAttributeValue (null, this, member.MemberType);
                        }
-                       
-                       return ((CLSCompliantAttribute)cls_attr [0]).IsCompliant;
                }
 
-               static bool AnalyzeTypeCompliance (Type type)
+               public void EncodeEmptyNamedArguments ()
+               {
+                       Encode ((ushort) 0);
+               }
+
+               void Grow (int inc)
+               {
+                       int size = System.Math.Max (pos * 4, pos + inc + 2);
+                       Array.Resize (ref buffer, size);
+               }
+
+               void WriteCompressedValue (int value)
                {
-                       type = TypeManager.DropGenericTypeArguments (type);
-                       DeclSpace ds = TypeManager.LookupDeclSpace (type);
-                       if (ds != null) {
-                               return ds.IsClsComplianceRequired ();
+                       if (value < 0x80) {
+                               Encode ((byte) value);
+                               return;
                        }
 
-                       if (TypeManager.IsGenericParameter (type))
-                               return true;
+                       if (value < 0x4000) {
+                               Encode ((byte) (0x80 | (value >> 8)));
+                               Encode ((byte) value);
+                               return;
+                       }
+
+                       Encode (value);
+               }
 
-                       return GetClsCompliantAttributeValue (type, type.Assembly);
+               public byte[] ToArray ()
+               {
+                       byte[] buf = new byte[pos];
+                       Array.Copy (buffer, buf, pos);
+                       return buf;
                }
+       }
 
+
+       /// <summary>
+       /// Helper class for attribute verification routine.
+       /// </summary>
+       static class AttributeTester
+       {
                /// <summary>
-               /// Returns instance of ObsoleteAttribute when type is obsolete
+               /// Common method for Obsolete error/warning reporting.
                /// </summary>
-               public static ObsoleteAttribute GetObsoleteAttribute (Type type)
+               public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc, Report Report)
                {
-                       object type_obsolete = analyzed_types_obsolete [type];
-                       if (type_obsolete == FALSE)
-                               return null;
+                       if (oa.IsError) {
+                               Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
+                               return;
+                       }
 
-                       if (type_obsolete != null)
-                               return (ObsoleteAttribute)type_obsolete;
+                       if (oa.Message == null || oa.Message.Length == 0) {
+                               Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
+                               return;
+                       }
+                       Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
+               }
+       }
 
-                       ObsoleteAttribute result = null;
-                       if (TypeManager.HasElementType (type)) {
-                               result = GetObsoleteAttribute (TypeManager.GetElementType (type));
-                       } else if (TypeManager.IsGenericParameter (type) || TypeManager.IsGenericType (type))
-                               return null;
-                       else {
-                               DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
-
-                               // Type is external, we can get attribute directly
-                               if (type_ds == null) {
-                                       if (TypeManager.obsolete_attribute_type != null) {
-                                               object [] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
-                                               if (attribute.Length == 1)
-                                                       result = (ObsoleteAttribute) attribute [0];
-                                       }
-                               } else {
-                                       result = type_ds.GetObsoleteAttribute ();
-                               }
+       //
+       // Predefined attribute types
+       //
+       public class PredefinedAttributes
+       {
+               // Build-in attributes
+               public readonly PredefinedAttribute ParamArray;
+               public readonly PredefinedAttribute Out;
+
+               // Optional attributes
+               public readonly PredefinedAttribute Obsolete;
+               public readonly PredefinedAttribute DllImport;
+               public readonly PredefinedAttribute MethodImpl;
+               public readonly PredefinedAttribute MarshalAs;
+               public readonly PredefinedAttribute In;
+               public readonly PredefinedAttribute IndexerName;
+               public readonly PredefinedAttribute Conditional;
+               public readonly PredefinedAttribute CLSCompliant;
+               public readonly PredefinedAttribute Security;
+               public readonly PredefinedAttribute Required;
+               public readonly PredefinedAttribute Guid;
+               public readonly PredefinedAttribute AssemblyCulture;
+               public readonly PredefinedAttribute AssemblyVersion;
+               public readonly PredefinedAttribute AssemblyAlgorithmId;
+               public readonly PredefinedAttribute AssemblyFlags;
+               public readonly PredefinedAttribute AssemblyFileVersion;
+               public readonly PredefinedAttribute ComImport;
+               public readonly PredefinedAttribute CoClass;
+               public readonly PredefinedAttribute AttributeUsage;
+               public readonly PredefinedAttribute DefaultParameterValue;
+               public readonly PredefinedAttribute OptionalParameter;
+               public readonly PredefinedAttribute UnverifiableCode;
+               public readonly PredefinedAttribute DefaultCharset;
+               public readonly PredefinedAttribute TypeForwarder;
+               public readonly PredefinedAttribute FixedBuffer;
+               public readonly PredefinedAttribute CompilerGenerated;
+               public readonly PredefinedAttribute InternalsVisibleTo;
+               public readonly PredefinedAttribute RuntimeCompatibility;
+               public readonly PredefinedAttribute DebuggerHidden;
+               public readonly PredefinedAttribute UnsafeValueType;
+               public readonly PredefinedAttribute UnmanagedFunctionPointer;
+               public readonly PredefinedDebuggerBrowsableAttribute DebuggerBrowsable;
+
+               // New in .NET 3.5
+               public readonly PredefinedAttribute Extension;
+
+               // New in .NET 4.0
+               public readonly PredefinedDynamicAttribute Dynamic;
+
+               //
+               // Optional types which are used as types and for member lookup
+               //
+               public readonly PredefinedAttribute DefaultMember;
+               public readonly PredefinedDecimalAttribute DecimalConstant;
+               public readonly PredefinedAttribute StructLayout;
+               public readonly PredefinedAttribute FieldOffset;
+               public readonly PredefinedAttribute CallerMemberNameAttribute;
+               public readonly PredefinedAttribute CallerLineNumberAttribute;
+               public readonly PredefinedAttribute CallerFilePathAttribute;
+
+               public PredefinedAttributes (ModuleContainer module)
+               {
+                       ParamArray = new PredefinedAttribute (module, "System", "ParamArrayAttribute");
+                       Out = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OutAttribute");
+                       ParamArray.Resolve ();
+                       Out.Resolve ();
+
+                       Obsolete = new PredefinedAttribute (module, "System", "ObsoleteAttribute");
+                       DllImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DllImportAttribute");
+                       MethodImpl = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "MethodImplAttribute");
+                       MarshalAs = new PredefinedAttribute (module, "System.Runtime.InteropServices", "MarshalAsAttribute");
+                       In = new PredefinedAttribute (module, "System.Runtime.InteropServices", "InAttribute");
+                       IndexerName = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "IndexerNameAttribute");
+                       Conditional = new PredefinedAttribute (module, "System.Diagnostics", "ConditionalAttribute");
+                       CLSCompliant = new PredefinedAttribute (module, "System", "CLSCompliantAttribute");
+                       Security = new PredefinedAttribute (module, "System.Security.Permissions", "SecurityAttribute");
+                       Required = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RequiredAttributeAttribute");
+                       Guid = new PredefinedAttribute (module, "System.Runtime.InteropServices", "GuidAttribute");
+                       AssemblyCulture = new PredefinedAttribute (module, "System.Reflection", "AssemblyCultureAttribute");
+                       AssemblyVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyVersionAttribute");
+                       AssemblyAlgorithmId = new PredefinedAttribute (module, "System.Reflection", "AssemblyAlgorithmIdAttribute");
+                       AssemblyFlags = new PredefinedAttribute (module, "System.Reflection", "AssemblyFlagsAttribute");
+                       AssemblyFileVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyFileVersionAttribute");
+                       ComImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "ComImportAttribute");
+                       CoClass = new PredefinedAttribute (module, "System.Runtime.InteropServices", "CoClassAttribute");
+                       AttributeUsage = new PredefinedAttribute (module, "System", "AttributeUsageAttribute");
+                       DefaultParameterValue = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultParameterValueAttribute");
+                       OptionalParameter = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OptionalAttribute");
+                       UnverifiableCode = new PredefinedAttribute (module, "System.Security", "UnverifiableCodeAttribute");
+
+                       DefaultCharset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultCharSetAttribute");
+                       TypeForwarder = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "TypeForwardedToAttribute");
+                       FixedBuffer = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "FixedBufferAttribute");
+                       CompilerGenerated = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
+                       InternalsVisibleTo = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
+                       RuntimeCompatibility = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
+                       DebuggerHidden = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerHiddenAttribute");
+                       UnsafeValueType = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
+                       UnmanagedFunctionPointer = new PredefinedAttribute (module, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
+                       DebuggerBrowsable = new PredefinedDebuggerBrowsableAttribute (module, "System.Diagnostics", "DebuggerBrowsableAttribute");
+
+                       Extension = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "ExtensionAttribute");
+
+                       Dynamic = new PredefinedDynamicAttribute (module, "System.Runtime.CompilerServices", "DynamicAttribute");
+
+                       DefaultMember = new PredefinedAttribute (module, "System.Reflection", "DefaultMemberAttribute");
+                       DecimalConstant = new PredefinedDecimalAttribute (module, "System.Runtime.CompilerServices", "DecimalConstantAttribute");
+                       StructLayout = new PredefinedAttribute (module, "System.Runtime.InteropServices", "StructLayoutAttribute");
+                       FieldOffset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "FieldOffsetAttribute");
+
+                       CallerMemberNameAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerMemberNameAttribute");
+                       CallerLineNumberAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerLineNumberAttribute");
+                       CallerFilePathAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerFilePathAttribute");
+
+                       // TODO: Should define only attributes which are used for comparison
+                       const System.Reflection.BindingFlags all_fields = System.Reflection.BindingFlags.Public |
+                               System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly;
+
+                       foreach (var fi in GetType ().GetFields (all_fields)) {
+                               ((PredefinedAttribute) fi.GetValue (this)).Define ();
                        }
+               }
+       }
+
+       public class PredefinedAttribute : PredefinedType
+       {
+               protected MethodSpec ctor;
 
-                       // Cannot use .Add because of corlib bootstrap
-                       analyzed_types_obsolete [type] = result == null ? FALSE : result;
-                       return result;
+               public PredefinedAttribute (ModuleContainer module, string ns, string name)
+                       : base (module, MemberKind.Class, ns, name)
+               {
                }
 
-               /// <summary>
-               /// Returns instance of ObsoleteAttribute when method is obsolete
-               /// </summary>
-               public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
+               #region Properties
+
+               public MethodSpec Constructor {
+                       get {
+                               return ctor;
+                       }
+               }
+
+               #endregion
+
+               public static bool operator == (TypeSpec type, PredefinedAttribute pa)
                {
-                       IMethodData mc = TypeManager.GetMethod (mb);
-                       if (mc != null) 
-                               return mc.GetObsoleteAttribute ();
+                       return type == pa.type && pa.type != null;
+               }
 
-                       // compiler generated methods are not registered by AddMethod
-                       if (mb.DeclaringType is TypeBuilder)
-                               return null;
+               public static bool operator != (TypeSpec type, PredefinedAttribute pa)
+               {
+                       return type != pa.type;
+               }
+
+               public override int GetHashCode ()
+               {
+                       return base.GetHashCode ();
+               }
 
-                       MemberInfo mi = TypeManager.GetPropertyFromAccessor (mb);
-                       if (mi != null)
-                               return GetMemberObsoleteAttribute (mi);
+               public override bool Equals (object obj)
+               {
+                       throw new NotSupportedException ();
+               }
 
-                       mi = TypeManager.GetEventFromAccessor (mb);
-                       if (mi != null)
-                               return GetMemberObsoleteAttribute (mi);
+               public void EmitAttribute (ConstructorBuilder builder)
+               {
+                       if (ResolveBuilder ())
+                               builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+               }
 
-                       return GetMemberObsoleteAttribute (mb);
+               public void EmitAttribute (MethodBuilder builder)
+               {
+                       if (ResolveBuilder ())
+                               builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
                }
 
-               /// <summary>
-               /// Returns instance of ObsoleteAttribute when member is obsolete
-               /// </summary>
-               public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
+               public void EmitAttribute (PropertyBuilder builder)
                {
-                       object type_obsolete = analyzed_member_obsolete [mi];
-                       if (type_obsolete == FALSE)
-                               return null;
+                       if (ResolveBuilder ())
+                               builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+               }
 
-                       if (type_obsolete != null)
-                               return (ObsoleteAttribute)type_obsolete;
+               public void EmitAttribute (FieldBuilder builder)
+               {
+                       if (ResolveBuilder ())
+                               builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+               }
 
-                       if ((mi.DeclaringType is TypeBuilder) || TypeManager.IsGenericType (mi.DeclaringType))
-                               return null;
+               public void EmitAttribute (TypeBuilder builder)
+               {
+                       if (ResolveBuilder ())
+                               builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+               }
 
-                       if (TypeManager.obsolete_attribute_type == null)
-                               return null;
+               public void EmitAttribute (AssemblyBuilder builder)
+               {
+                       if (ResolveBuilder ())
+                               builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+               }
 
-                       ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false)
-                               as ObsoleteAttribute;
-                       analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
-                       return oa;
+               public void EmitAttribute (ModuleBuilder builder)
+               {
+                       if (ResolveBuilder ())
+                               builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
                }
 
-               /// <summary>
-               /// Common method for Obsolete error/warning reporting.
-               /// </summary>
-               public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
+               public void EmitAttribute (ParameterBuilder builder)
                {
-                       if (oa.IsError) {
-                               Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
+                       if (ResolveBuilder ())
+                               builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+               }
+
+               ConstructorInfo GetCtorMetaInfo ()
+               {
+                       return (ConstructorInfo) ctor.GetMetaInfo ();
+               }
+
+               public bool ResolveBuilder ()
+               {
+                       if (ctor != null)
+                               return true;
+
+                       //
+                       // Handle all parameter-less attributes as optional
+                       //
+                       if (!IsDefined)
+                               return false;
+
+                       ctor = (MethodSpec) MemberCache.FindMember (type, MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters), BindingRestriction.DeclaredOnly);
+                       return ctor != null;
+               }
+       }
+
+       public class PredefinedDebuggerBrowsableAttribute : PredefinedAttribute
+       {
+               public PredefinedDebuggerBrowsableAttribute (ModuleContainer module, string ns, string name)
+                       : base (module, ns, name)
+               {
+               }
+
+               public void EmitAttribute (FieldBuilder builder, System.Diagnostics.DebuggerBrowsableState state)
+               {
+                       var ctor = module.PredefinedMembers.DebuggerBrowsableAttributeCtor.Get ();
+                       if (ctor == null)
                                return;
-                       }
 
-                       if (oa.Message == null || oa.Message.Length == 0) {
-                               Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
+                       AttributeEncoder encoder = new AttributeEncoder ();
+                       encoder.Encode ((int) state);
+                       encoder.EncodeEmptyNamedArguments ();
+
+                       builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
+               }
+       }
+
+       public class PredefinedDecimalAttribute : PredefinedAttribute
+       {
+               public PredefinedDecimalAttribute (ModuleContainer module, string ns, string name)
+                       : base (module, ns, name)
+               {
+               }
+
+               public void EmitAttribute (ParameterBuilder builder, decimal value, Location loc)
+               {
+                       var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
+                       if (ctor == null)
                                return;
-                       }
-                       Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
+
+                       int[] bits = decimal.GetBits (value);
+                       AttributeEncoder encoder = new AttributeEncoder ();
+                       encoder.Encode ((byte) (bits[3] >> 16));
+                       encoder.Encode ((byte) (bits[3] >> 31));
+                       encoder.Encode ((uint) bits[2]);
+                       encoder.Encode ((uint) bits[1]);
+                       encoder.Encode ((uint) bits[0]);
+                       encoder.EncodeEmptyNamedArguments ();
+
+                       builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
                }
 
-               public static bool IsConditionalMethodExcluded (MethodBase mb, Location loc)
+               public void EmitAttribute (FieldBuilder builder, decimal value, Location loc)
                {
-                       object excluded = analyzed_method_excluded [mb];
-                       if (excluded != null)
-                               return excluded == TRUE ? true : false;
+                       var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
+                       if (ctor == null)
+                               return;
 
-                       if (TypeManager.conditional_attribute_type == null)
-                               return false;
+                       int[] bits = decimal.GetBits (value);
+                       AttributeEncoder encoder = new AttributeEncoder ();
+                       encoder.Encode ((byte) (bits[3] >> 16));
+                       encoder.Encode ((byte) (bits[3] >> 31));
+                       encoder.Encode ((uint) bits[2]);
+                       encoder.Encode ((uint) bits[1]);
+                       encoder.Encode ((uint) bits[0]);
+                       encoder.EncodeEmptyNamedArguments ();
 
-                       ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true)
-                               as ConditionalAttribute[];
-                       if (attrs.Length == 0) {
-                               analyzed_method_excluded.Add (mb, FALSE);
-                               return false;
-                       }
+                       builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
+               }
+       }
 
-                       foreach (ConditionalAttribute a in attrs) {
-                               if (loc.CompilationUnit.IsConditionalDefined (a.ConditionString)) {
-                                       analyzed_method_excluded.Add (mb, FALSE);
-                                       return false;
-                               }
-                       }
+       public class PredefinedDynamicAttribute : PredefinedAttribute
+       {
+               MethodSpec tctor;
 
-                       analyzed_method_excluded.Add (mb, TRUE);
-                       return true;
+               public PredefinedDynamicAttribute (ModuleContainer module, string ns, string name)
+                       : base (module, ns, name)
+               {
                }
 
-               /// <summary>
-               /// Analyzes class whether it has attribute which has ConditionalAttribute
-               /// and its condition is not defined.
-               /// </summary>
-               public static bool IsAttributeExcluded (Type type, Location loc)
+               public void EmitAttribute (FieldBuilder builder, TypeSpec type, Location loc)
                {
-                       if (!type.IsClass)
-                               return false;
+                       if (ResolveTransformationCtor (loc)) {
+                               var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
+                               builder.SetCustomAttribute (cab);
+                       }
+               }
 
-                       Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
+               public void EmitAttribute (ParameterBuilder builder, TypeSpec type, Location loc)
+               {
+                       if (ResolveTransformationCtor (loc)) {
+                               var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
+                               builder.SetCustomAttribute (cab);
+                       }
+               }
 
-                       // TODO: add caching
-                       // TODO: merge all Type bases attribute caching to one cache to save memory
-                       if (class_decl == null && TypeManager.conditional_attribute_type != null) {
-                               object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
-                               foreach (ConditionalAttribute ca in attributes) {
-                                       if (loc.CompilationUnit.IsConditionalDefined (ca.ConditionString))
-                                               return false;
-                               }
-                               return attributes.Length > 0;
+               public void EmitAttribute (PropertyBuilder builder, TypeSpec type, Location loc)
+               {
+                       if (ResolveTransformationCtor (loc)) {
+                               var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
+                               builder.SetCustomAttribute (cab);
                        }
+               }
 
-                       return class_decl.IsExcluded ();
+               public void EmitAttribute (TypeBuilder builder, TypeSpec type, Location loc)
+               {
+                       if (ResolveTransformationCtor (loc)) {
+                               var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
+                               builder.SetCustomAttribute (cab);
+                       }
                }
 
-               public static Type GetCoClassAttribute (Type type)
+               //
+               // When any element of the type is a dynamic type
+               //
+               // This method builds a transformation array for dynamic types
+               // used in places where DynamicAttribute cannot be applied to.
+               // It uses bool flag when type is of dynamic type and each
+               // section always starts with "false" for some reason.
+               //
+               // LAMESPEC: This should be part of C# specification
+               // 
+               // Example: Func<dynamic, int, dynamic[]>
+               // Transformation: { false, true, false, false, true }
+               //
+               static bool[] GetTransformationFlags (TypeSpec t)
                {
-                       TypeContainer tc = TypeManager.LookupInterface (type);
-                       if (tc == null) {
-                               if (TypeManager.coclass_attr_type == null)
+                       bool[] element;
+                       var ac = t as ArrayContainer;
+                       if (ac != null) {
+                               element = GetTransformationFlags (ac.Element);
+                               if (element == null)
                                        return null;
 
-                               object[] o = type.GetCustomAttributes (TypeManager.coclass_attr_type, false);
-                               if (o.Length < 1)
-                                       return null;
-                               return ((System.Runtime.InteropServices.CoClassAttribute)o[0]).CoClass;
+                               bool[] res = new bool[element.Length + 1];
+                               res[0] = false;
+                               Array.Copy (element, 0, res, 1, element.Length);
+                               return res;
                        }
 
-                       if (tc.OptAttributes == null || TypeManager.coclass_attr_type == null)
+                       if (t == null)
                                return null;
 
-                       Attribute a = tc.OptAttributes.Search (TypeManager.coclass_attr_type);
-                       if (a == null)
-                               return null;
+                       if (t.IsGeneric) {
+                               List<bool> transform = null;
+                               var targs = t.TypeArguments;
+                               for (int i = 0; i < targs.Length; ++i) {
+                                       element = GetTransformationFlags (targs[i]);
+                                       if (element != null) {
+                                               if (transform == null) {
+                                                       transform = new List<bool> ();
+                                                       for (int ii = 0; ii <= i; ++ii)
+                                                               transform.Add (false);
+                                               }
+
+                                               transform.AddRange (element);
+                                       } else if (transform != null) {
+                                               transform.Add (false);
+                                       }
+                               }
+
+                               if (transform != null)
+                                       return transform.ToArray ();
+                       }
+
+                       if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+                               return new bool[] { true };
+
+                       return null;
+               }
+
+               bool ResolveTransformationCtor (Location loc)
+               {
+                       if (tctor != null)
+                               return true;
 
-                       return a.GetCoClassAttributeValue ();
+                       tctor = module.PredefinedMembers.DynamicAttributeCtor.Resolve (loc);
+                       return tctor != null;
                }
        }
 }