コード例 #1
0
 private void WriteEnumerationData(EnumNode enumeration) {
     TypeNode underlying = enumeration.UnderlyingType;
     if (underlying.FullName != "System.Int32") {
         writer.WriteStartElement("enumerationbase");
         WriteTypeReference(enumeration.UnderlyingType);
         writer.WriteEndElement();
     }
 }
コード例 #2
0
ファイル: Rewriter.cs プロジェクト: nbulp/CodeContracts
    /// <summary>
    /// Tries to reuse or create the attribute
    /// </summary>
    private static InstanceInitializer GetRuntimeContractsAttributeCtor(AssemblyNode assembly)
    {
      EnumNode runtimeContractsFlags = assembly.GetType(ContractNodes.ContractNamespace, Identifier.For("RuntimeContractsFlags")) as EnumNode;
      Class RuntimeContractsAttributeClass = assembly.GetType(ContractNodes.ContractNamespace, Identifier.For("RuntimeContractsAttribute")) as Class;

      if (runtimeContractsFlags == null)
      {
        #region Add [Flags]
        Member flagsConstructor = RewriteHelper.flagsAttributeNode.GetConstructor();
        AttributeNode flagsAttribute = new AttributeNode(new MemberBinding(null, flagsConstructor), null, AttributeTargets.Class);
        #endregion Add [Flags]
        runtimeContractsFlags = new EnumNode(assembly,
          null, /* declaringType */
          new AttributeList(2),
          TypeFlags.Sealed,
          ContractNodes.ContractNamespace,
          Identifier.For("RuntimeContractsFlags"),
          new InterfaceList(),
          new MemberList());
        runtimeContractsFlags.Attributes.Add(flagsAttribute);
        RewriteHelper.TryAddCompilerGeneratedAttribute(runtimeContractsFlags);
        runtimeContractsFlags.UnderlyingType = SystemTypes.Int32;

        Type copyFrom = typeof(RuntimeContractEmitFlags);
        foreach (System.Reflection.FieldInfo fi in copyFrom.GetFields())
        {
          if (fi.IsLiteral)
          {
            AddEnumValue(runtimeContractsFlags, fi.Name, fi.GetRawConstantValue());
          }
        }
        assembly.Types.Add(runtimeContractsFlags);

      }


      InstanceInitializer ctor = (RuntimeContractsAttributeClass == null) ? null : RuntimeContractsAttributeClass.GetConstructor(runtimeContractsFlags);

      if (RuntimeContractsAttributeClass == null)
      {
        RuntimeContractsAttributeClass = new Class(assembly,
          null, /* declaringType */
          new AttributeList(),
          TypeFlags.Sealed,
          ContractNodes.ContractNamespace,
          Identifier.For("RuntimeContractsAttribute"),
          SystemTypes.Attribute,
          new InterfaceList(),
          new MemberList(0));

        RewriteHelper.TryAddCompilerGeneratedAttribute(RuntimeContractsAttributeClass);
        assembly.Types.Add(RuntimeContractsAttributeClass);
      }
      if (ctor == null) {

        Block returnBlock = new Block(new StatementList(new Return()));

        Block body = new Block(new StatementList());
        Block b = new Block(new StatementList());
        ParameterList pl = new ParameterList();
        Parameter levelParameter = new Parameter(Identifier.For("contractFlags"), runtimeContractsFlags);
        pl.Add(levelParameter);

        ctor = new InstanceInitializer(RuntimeContractsAttributeClass, null, pl, body);
        ctor.Flags = MethodFlags.Assembly | MethodFlags.HideBySig | MethodFlags.SpecialName | MethodFlags.RTSpecialName;

        Method baseCtor = SystemTypes.Attribute.GetConstructor();

        b.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(null, baseCtor), new ExpressionList(ctor.ThisParameter))));
        b.Statements.Add(returnBlock);
        body.Statements.Add(b);

        RuntimeContractsAttributeClass.Members.Add(ctor);
      }

      return ctor;
    }
コード例 #3
0
ファイル: SystemTypes.cs プロジェクト: armin-bauer/SHFB
        private static void ClearStatics()
        {
            AttributeUsageAttribute = null;
            ConditionalAttribute = null;
            DefaultMemberAttribute = null;
            InternalsVisibleToAttribute = null;
            ObsoleteAttribute = null;

            GenericICollection = null;
            GenericIEnumerable = null;
            GenericIList = null;
            ICloneable = null;
            ICollection = null;
            IEnumerable = null;
            IList = null;

            //Special attributes    
            AllowPartiallyTrustedCallersAttribute = null;
            AssemblyCompanyAttribute = null;
            AssemblyConfigurationAttribute = null;
            AssemblyCopyrightAttribute = null;
            AssemblyCultureAttribute = null;
            AssemblyDelaySignAttribute = null;
            AssemblyDescriptionAttribute = null;
            AssemblyFileVersionAttribute = null;
            AssemblyFlagsAttribute = null;
            AssemblyInformationalVersionAttribute = null;
            AssemblyKeyFileAttribute = null;
            AssemblyKeyNameAttribute = null;
            AssemblyProductAttribute = null;
            AssemblyTitleAttribute = null;
            AssemblyTrademarkAttribute = null;
            AssemblyVersionAttribute = null;
            ClassInterfaceAttribute = null;
            CLSCompliantAttribute = null;
            ComImportAttribute = null;
            ComRegisterFunctionAttribute = null;
            ComSourceInterfacesAttribute = null;
            ComUnregisterFunctionAttribute = null;
            ComVisibleAttribute = null;
            DebuggableAttribute = null;
            DebuggerHiddenAttribute = null;
            DebuggerStepThroughAttribute = null;
            DebuggingModes = null;
            DllImportAttribute = null;
            FieldOffsetAttribute = null;
            FlagsAttribute = null;
            GuidAttribute = null;
            ImportedFromTypeLibAttribute = null;
            InAttribute = null;
            IndexerNameAttribute = null;
            InterfaceTypeAttribute = null;
            MethodImplAttribute = null;
            NonSerializedAttribute = null;
            OptionalAttribute = null;
            OutAttribute = null;
            ParamArrayAttribute = null;
            RuntimeCompatibilityAttribute = null;
            SatelliteContractVersionAttribute = null;
            SerializableAttribute = null;
            SecurityAttribute = null;
            SecurityCriticalAttribute = null;
            SecurityTransparentAttribute = null;
            SecurityTreatAsSafeAttribute = null;
            STAThreadAttribute = null;
            StructLayoutAttribute = null;
            SuppressMessageAttribute = null;
            SuppressUnmanagedCodeSecurityAttribute = null;
            SecurityAction = null;

            //Classes need for System.TypeCode
            DBNull = null;
            DateTime = null;
            TimeSpan = null;

            //Classes and interfaces used by the Framework
            Activator = null;
            AppDomain = null;
            ApplicationException = null;
            ArgumentException = null;
            ArgumentNullException = null;
            ArgumentOutOfRangeException = null;
            ArrayList = null;
            AsyncCallback = null;
            Assembly = null;
            CodeAccessPermission = null;
            CollectionBase = null;
            CultureInfo = null;
            DictionaryBase = null;
            DictionaryEntry = null;
            DuplicateWaitObjectException = null;
            Environment = null;
            EventArgs = null;
            ExecutionEngineException = null;
            GenericArraySegment = null;
            GenericArrayToIEnumerableAdapter = null;
            GenericDictionary = null;
            GenericIComparable = null;
            GenericIComparer = null;
            GenericIDictionary = null;
            GenericIEnumerator = null;
            GenericKeyValuePair = null;
            GenericList = null;
            GenericNullable = null;
            GenericQueue = null;
            GenericSortedDictionary = null;
            GenericStack = null;
            GC = null;
            Guid = null;
            __HandleProtector = null;
            HandleRef = null;
            Hashtable = null;
            IASyncResult = null;
            IComparable = null;
            IDictionary = null;
            IComparer = null;
            IDisposable = null;
            IEnumerator = null;
            IFormatProvider = null;
            IHashCodeProvider = null;
            IMembershipCondition = null;
            IndexOutOfRangeException = null;
            InvalidCastException = null;
            InvalidOperationException = null;
            IPermission = null;
            ISerializable = null;
            IStackWalk = null;
            Marshal = null;
            MarshalByRefObject = null;
            MemberInfo = null;
            NativeOverlapped = null;
            Monitor = null;
            NotSupportedException = null;
            NullReferenceException = null;
            OutOfMemoryException = null;
            ParameterInfo = null;
            Queue = null;
            ReadOnlyCollectionBase = null;
            ResourceManager = null;
            ResourceSet = null;
            SerializationInfo = null;
            Stack = null;
            StackOverflowException = null;
            Stream = null;
            StreamingContext = null;
            StringBuilder = null;
            StringComparer = null;
            StringComparison = null;
            SystemException = null;
            Thread = null;
            WindowsImpersonationContext = null;
        }
コード例 #4
0
 private static FieldList GetAppliedFields(EnumNode enumeration, long value) {
     // if a single field matches, return it;
     // otherwise return all fields that are in value
     FieldList list = new FieldList();
     MemberList members = enumeration.Members;
     for (int i = 0; i < members.Count; i++) {
         if (members[i].NodeType != NodeType.Field) continue;
         Field field = (Field)members[i];
         if (field.DefaultValue == null) continue;
         long fieldValue = Convert.ToInt64(field.DefaultValue.Value);
         if (fieldValue == value) {
             return (new FieldList(new Field[1] { field }));
         } else if ((fieldValue & value) == fieldValue) {
             list.Add(field);
         }
     }
     return (list);
 }
コード例 #5
0
    public override EnumNode VisitEnumNode(EnumNode enumNode) {
      if (enumNode == null || enumNode.SourceContext.SourceText == null) return null;
      this.writer.WriteStartElement("Enum");
      this.writer.WriteAttributeString("name", enumNode.Name.Name);
      this.WriteSourceContext(enumNode);

      this.writer.WriteEndElement(); // Enum
      return enumNode;
    }
コード例 #6
0
ファイル: SystemTypes.cs プロジェクト: armin-bauer/SHFB
        public static void Initialize(bool doNotLockFile, bool getDebugInfo)
        {
            if (SystemTypes.Initialized)
            {
                SystemTypes.Clear();
                CoreSystemTypes.Initialize(doNotLockFile, getDebugInfo);
            }
            else if (!CoreSystemTypes.Initialized)
            {
                CoreSystemTypes.Initialize(doNotLockFile, getDebugInfo);
            }

            if (TargetPlatform.TargetVersion == null)
            {
                TargetPlatform.TargetVersion = SystemAssembly.Version;
                if (TargetPlatform.TargetVersion == null)
                    TargetPlatform.TargetVersion = typeof(object).Module.Assembly.GetName().Version;
            }
            //TODO: throw an exception when the result is null

            AttributeUsageAttribute = (Class)GetTypeNodeFor("System", "AttributeUsageAttribute", ElementType.Class);
            ConditionalAttribute = (Class)GetTypeNodeFor("System.Diagnostics", "ConditionalAttribute", ElementType.Class);
            DefaultMemberAttribute = (Class)GetTypeNodeFor("System.Reflection", "DefaultMemberAttribute", ElementType.Class);
            InternalsVisibleToAttribute = (Class)GetTypeNodeFor("System.Runtime.CompilerServices", "InternalsVisibleToAttribute", ElementType.Class);
            ObsoleteAttribute = (Class)GetTypeNodeFor("System", "ObsoleteAttribute", ElementType.Class);

            GenericICollection = (Interface)GetGenericRuntimeTypeNodeFor("System.Collections.Generic", "ICollection", 1, ElementType.Class);
            GenericIEnumerable = (Interface)GetGenericRuntimeTypeNodeFor("System.Collections.Generic", "IEnumerable", 1, ElementType.Class);
            GenericIList = (Interface)GetGenericRuntimeTypeNodeFor("System.Collections.Generic", "IList", 1, ElementType.Class);
            ICloneable = (Interface)GetTypeNodeFor("System", "ICloneable", ElementType.Class);
            ICollection = (Interface)GetTypeNodeFor("System.Collections", "ICollection", ElementType.Class);
            IEnumerable = (Interface)GetTypeNodeFor("System.Collections", "IEnumerable", ElementType.Class);
            IList = (Interface)GetTypeNodeFor("System.Collections", "IList", ElementType.Class);

            AllowPartiallyTrustedCallersAttribute = (Class)GetTypeNodeFor("System.Security", "AllowPartiallyTrustedCallersAttribute", ElementType.Class);
            AssemblyCompanyAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyCompanyAttribute", ElementType.Class);
            AssemblyConfigurationAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyConfigurationAttribute", ElementType.Class);
            AssemblyCopyrightAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyCopyrightAttribute", ElementType.Class);
            AssemblyCultureAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyCultureAttribute", ElementType.Class);
            AssemblyDelaySignAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyDelaySignAttribute", ElementType.Class);
            AssemblyDescriptionAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyDescriptionAttribute", ElementType.Class);
            AssemblyFileVersionAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyFileVersionAttribute", ElementType.Class);
            AssemblyFlagsAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyFlagsAttribute", ElementType.Class);
            AssemblyInformationalVersionAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyInformationalVersionAttribute", ElementType.Class);
            AssemblyKeyFileAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyKeyFileAttribute", ElementType.Class);
            AssemblyKeyNameAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyKeyNameAttribute", ElementType.Class);
            AssemblyProductAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyProductAttribute", ElementType.Class);
            AssemblyTitleAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyTitleAttribute", ElementType.Class);
            AssemblyTrademarkAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyTrademarkAttribute", ElementType.Class);
            AssemblyVersionAttribute = (Class)GetTypeNodeFor("System.Reflection", "AssemblyVersionAttribute", ElementType.Class);
            ClassInterfaceAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "ClassInterfaceAttribute", ElementType.Class);
            CLSCompliantAttribute = (Class)GetTypeNodeFor("System", "CLSCompliantAttribute", ElementType.Class);
            ComImportAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "ComImportAttribute", ElementType.Class);
            ComRegisterFunctionAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "ComRegisterFunctionAttribute", ElementType.Class);
            ComSourceInterfacesAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "ComSourceInterfacesAttribute", ElementType.Class);
            ComUnregisterFunctionAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "ComUnregisterFunctionAttribute", ElementType.Class);
            ComVisibleAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "ComVisibleAttribute", ElementType.Class);
            DebuggableAttribute = (Class)GetTypeNodeFor("System.Diagnostics", "DebuggableAttribute", ElementType.Class);
            DebuggerHiddenAttribute = (Class)GetTypeNodeFor("System.Diagnostics", "DebuggerHiddenAttribute", ElementType.Class);
            DebuggerStepThroughAttribute = (Class)GetTypeNodeFor("System.Diagnostics", "DebuggerStepThroughAttribute", ElementType.Class);
            DebuggingModes = DebuggableAttribute == null ? null : DebuggableAttribute.GetNestedType(Identifier.For("DebuggingModes")) as EnumNode;
            DllImportAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "DllImportAttribute", ElementType.Class);
            FieldOffsetAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "FieldOffsetAttribute", ElementType.Class);
            FlagsAttribute = (Class)GetTypeNodeFor("System", "FlagsAttribute", ElementType.Class);
            Guid = (Struct)GetTypeNodeFor("System", "Guid", ElementType.ValueType);
            GuidAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "GuidAttribute", ElementType.Class);
            ImportedFromTypeLibAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "ImportedFromTypeLibAttribute", ElementType.Class);
            InAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "InAttribute", ElementType.Class);
            IndexerNameAttribute = (Class)GetTypeNodeFor("System.Runtime.CompilerServices", "IndexerNameAttribute", ElementType.Class);
            InterfaceTypeAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "InterfaceTypeAttribute", ElementType.Class);
            MethodImplAttribute = (Class)GetTypeNodeFor("System.Runtime.CompilerServices", "MethodImplAttribute", ElementType.Class);
            NonSerializedAttribute = (Class)GetTypeNodeFor("System", "NonSerializedAttribute", ElementType.Class);
            OptionalAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "OptionalAttribute", ElementType.Class);
            OutAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "OutAttribute", ElementType.Class);
            ParamArrayAttribute = (Class)GetTypeNodeFor("System", "ParamArrayAttribute", ElementType.Class);
            RuntimeCompatibilityAttribute = (Class)GetTypeNodeFor("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute", ElementType.Class);
            SatelliteContractVersionAttribute = (Class)GetTypeNodeFor("System.Resources", "SatelliteContractVersionAttribute", ElementType.Class);
            SerializableAttribute = (Class)GetTypeNodeFor("System", "SerializableAttribute", ElementType.Class);
            SecurityAttribute = (Class)GetTypeNodeFor("System.Security.Permissions", "SecurityAttribute", ElementType.Class);
            SecurityCriticalAttribute = (Class)GetTypeNodeFor("System.Security", "SecurityCriticalAttribute", ElementType.Class);
            SecurityTransparentAttribute = (Class)GetTypeNodeFor("System.Security", "SecurityTransparentAttribute", ElementType.Class);
            SecurityTreatAsSafeAttribute = (Class)GetTypeNodeFor("System.Security", "SecurityTreatAsSafeAttribute", ElementType.Class);
            STAThreadAttribute = (Class)GetTypeNodeFor("System", "STAThreadAttribute", ElementType.Class);
            StructLayoutAttribute = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "StructLayoutAttribute", ElementType.Class);
            SuppressMessageAttribute = (Class)GetTypeNodeFor("System.Diagnostics.CodeAnalysis", "SuppressMessageAttribute", ElementType.Class);
            SuppressUnmanagedCodeSecurityAttribute = (Class)GetTypeNodeFor("System.Security", "SuppressUnmanagedCodeSecurityAttribute", ElementType.Class);
            SecurityAction = GetTypeNodeFor("System.Security.Permissions", "SecurityAction", ElementType.ValueType) as EnumNode;
            DBNull = (Class)GetTypeNodeFor("System", "DBNull", ElementType.Class);
            DateTime = (Struct)GetTypeNodeFor("System", "DateTime", ElementType.ValueType);
            TimeSpan = (Struct)GetTypeNodeFor("System", "TimeSpan", ElementType.ValueType);
            Activator = (Class)GetTypeNodeFor("System", "Activator", ElementType.Class);
            AppDomain = (Class)GetTypeNodeFor("System", "AppDomain", ElementType.Class);
            ApplicationException = (Class)GetTypeNodeFor("System", "ApplicationException", ElementType.Class);
            ArgumentException = (Class)GetTypeNodeFor("System", "ArgumentException", ElementType.Class);
            ArgumentNullException = (Class)GetTypeNodeFor("System", "ArgumentNullException", ElementType.Class);
            ArgumentOutOfRangeException = (Class)GetTypeNodeFor("System", "ArgumentOutOfRangeException", ElementType.Class);
            ArrayList = (Class)GetTypeNodeFor("System.Collections", "ArrayList", ElementType.Class);
            AsyncCallback = (DelegateNode)GetTypeNodeFor("System", "AsyncCallback", ElementType.Class);
            Assembly = (Class)GetTypeNodeFor("System.Reflection", "Assembly", ElementType.Class);
            CodeAccessPermission = (Class)GetTypeNodeFor("System.Security", "CodeAccessPermission", ElementType.Class);
            CollectionBase = (Class)GetTypeNodeFor("System.Collections", "CollectionBase", ElementType.Class);
            CultureInfo = (Class)GetTypeNodeFor("System.Globalization", "CultureInfo", ElementType.Class);
            DictionaryBase = (Class)GetTypeNodeFor("System.Collections", "DictionaryBase", ElementType.Class);

            // EFW - In the .NET Micro Framework this is a class not a structure.  Few if any of these are
            // actually used, this one included.  I'm loathe to remove them as they may be used to ensure
            // assemblies are loaded.  Using the as operator rather than a direct cast prevent it from failing.
            DictionaryEntry = GetTypeNodeFor("System.Collections", "DictionaryEntry", ElementType.ValueType) as Struct;

            DuplicateWaitObjectException = (Class)GetTypeNodeFor("System", "DuplicateWaitObjectException", ElementType.Class);
            Environment = (Class)GetTypeNodeFor("System", "Environment", ElementType.Class);
            EventArgs = (Class)GetTypeNodeFor("System", "EventArgs", ElementType.Class);
            ExecutionEngineException = (Class)GetTypeNodeFor("System", "ExecutionEngineException", ElementType.Class);
            GenericArraySegment = (Struct)GetGenericRuntimeTypeNodeFor("System", "ArraySegment", 1, ElementType.ValueType);
            GenericDictionary = (Class)GetGenericRuntimeTypeNodeFor("System.Collections.Generic", "Dictionary", 2, ElementType.Class);
            GenericIComparable = (Interface)GetGenericRuntimeTypeNodeFor("System.Collections.Generic", "IComparable", 1, ElementType.Class);
            GenericIComparer = (Interface)GetGenericRuntimeTypeNodeFor("System.Collections.Generic", "IComparer", 1, ElementType.Class);
            GenericIDictionary = (Interface)GetGenericRuntimeTypeNodeFor("System.Collections.Generic", "IDictionary", 2, ElementType.Class);
            GenericIEnumerator = (Interface)GetGenericRuntimeTypeNodeFor("System.Collections.Generic", "IEnumerator", 1, ElementType.Class);
            GenericKeyValuePair = (Struct)GetGenericRuntimeTypeNodeFor("System.Collections.Generic", "KeyValuePair", 2, ElementType.ValueType);
            GenericList = (Class)GetGenericRuntimeTypeNodeFor("System.Collections.Generic", "List", 1, ElementType.Class);
            GenericNullable = (Struct)GetGenericRuntimeTypeNodeFor("System", "Nullable", 1, ElementType.ValueType);
            GenericQueue = (Class)GetGenericRuntimeTypeNodeFor("System.Collections.Generic", "Queue", 1, ElementType.Class);
            GenericSortedDictionary = (Class)GetGenericRuntimeTypeNodeFor("System.Collections.Generic", "SortedDictionary", 2, ElementType.Class);
            GenericStack = (Class)GetGenericRuntimeTypeNodeFor("System.Collections.Generic", "Stack", 1, ElementType.Class);
            GC = (Class)GetTypeNodeFor("System", "GC", ElementType.Class);
            __HandleProtector = (Class)GetTypeNodeFor("System.Threading", "__HandleProtector", ElementType.Class);
            HandleRef = (Struct)GetTypeNodeFor("System.Runtime.InteropServices", "HandleRef", ElementType.ValueType);
            Hashtable = (Class)GetTypeNodeFor("System.Collections", "Hashtable", ElementType.Class);
            IASyncResult = (Interface)GetTypeNodeFor("System", "IAsyncResult", ElementType.Class);
            IComparable = (Interface)GetTypeNodeFor("System", "IComparable", ElementType.Class);
            IComparer = (Interface)GetTypeNodeFor("System.Collections", "IComparer", ElementType.Class);
            IDictionary = (Interface)GetTypeNodeFor("System.Collections", "IDictionary", ElementType.Class);
            IDisposable = (Interface)GetTypeNodeFor("System", "IDisposable", ElementType.Class);
            IEnumerator = (Interface)GetTypeNodeFor("System.Collections", "IEnumerator", ElementType.Class);
            IFormatProvider = (Interface)GetTypeNodeFor("System", "IFormatProvider", ElementType.Class);
            IHashCodeProvider = (Interface)GetTypeNodeFor("System.Collections", "IHashCodeProvider", ElementType.Class);
            IMembershipCondition = (Interface)GetTypeNodeFor("System.Security.Policy", "IMembershipCondition", ElementType.Class);
            IndexOutOfRangeException = (Class)GetTypeNodeFor("System", "IndexOutOfRangeException", ElementType.Class);
            InvalidCastException = (Class)GetTypeNodeFor("System", "InvalidCastException", ElementType.Class);
            InvalidOperationException = (Class)GetTypeNodeFor("System", "InvalidOperationException", ElementType.Class);
            IPermission = (Interface)GetTypeNodeFor("System.Security", "IPermission", ElementType.Class);
            ISerializable = (Interface)GetTypeNodeFor("System.Runtime.Serialization", "ISerializable", ElementType.Class);
            IStackWalk = (Interface)GetTypeNodeFor("System.Security", "IStackWalk", ElementType.Class);
            Marshal = (Class)GetTypeNodeFor("System.Runtime.InteropServices", "Marshal", ElementType.Class);
            MarshalByRefObject = (Class)GetTypeNodeFor("System", "MarshalByRefObject", ElementType.Class);
            MemberInfo = (Class)GetTypeNodeFor("System.Reflection", "MemberInfo", ElementType.Class);
            Monitor = (Class)GetTypeNodeFor("System.Threading", "Monitor", ElementType.Class);
            NativeOverlapped = (Struct)GetTypeNodeFor("System.Threading", "NativeOverlapped", ElementType.ValueType);
            NotSupportedException = (Class)GetTypeNodeFor("System", "NotSupportedException", ElementType.Class);
            NullReferenceException = (Class)GetTypeNodeFor("System", "NullReferenceException", ElementType.Class);
            OutOfMemoryException = (Class)GetTypeNodeFor("System", "OutOfMemoryException", ElementType.Class);
            ParameterInfo = (Class)GetTypeNodeFor("System.Reflection", "ParameterInfo", ElementType.Class);
            Queue = (Class)GetTypeNodeFor("System.Collections", "Queue", ElementType.Class);
            ReadOnlyCollectionBase = (Class)GetTypeNodeFor("System.Collections", "ReadOnlyCollectionBase", ElementType.Class);
            ResourceManager = (Class)GetTypeNodeFor("System.Resources", "ResourceManager", ElementType.Class);
            ResourceSet = (Class)GetTypeNodeFor("System.Resources", "ResourceSet", ElementType.Class);
            SerializationInfo = (Class)GetTypeNodeFor("System.Runtime.Serialization", "SerializationInfo", ElementType.Class);
            Stack = (Class)GetTypeNodeFor("System.Collections", "Stack", ElementType.Class);
            StackOverflowException = (Class)GetTypeNodeFor("System", "StackOverflowException", ElementType.Class);
            Stream = (Class)GetTypeNodeFor("System.IO", "Stream", ElementType.Class);
            StreamingContext = (Struct)GetTypeNodeFor("System.Runtime.Serialization", "StreamingContext", ElementType.ValueType);
            StringBuilder = (Class)GetTypeNodeFor("System.Text", "StringBuilder", ElementType.Class);
            StringComparer = (Class)GetTypeNodeFor("System", "StringComparer", ElementType.Class);
            StringComparison = GetTypeNodeFor("System", "StringComparison", ElementType.ValueType) as EnumNode;
            SystemException = (Class)GetTypeNodeFor("System", "SystemException", ElementType.Class);
            Thread = (Class)GetTypeNodeFor("System.Threading", "Thread", ElementType.Class);
            WindowsImpersonationContext = (Class)GetTypeNodeFor("System.Security.Principal", "WindowsImpersonationContext", ElementType.Class);

            SystemTypes.Initialized = true;
            object dummy = TargetPlatform.AssemblyReferenceFor; //Force selection of target platform
            if (dummy == null) return;
        }
コード例 #7
0
ファイル: SystemTypes.cs プロジェクト: armin-bauer/SHFB
        public static void Initialize(bool doNotLockFile, bool getDebugInfo)
        {
            if (CoreSystemTypes.Initialized) CoreSystemTypes.Clear();
            if (SystemAssembly == null)
                SystemAssembly = CoreSystemTypes.GetSystemAssembly(doNotLockFile, getDebugInfo);
            if (SystemAssembly == null) throw new InvalidOperationException(ExceptionStrings.InternalCompilerError);
            if (TargetPlatform.TargetVersion == null)
            {
                TargetPlatform.TargetVersion = SystemAssembly.Version;
                if (TargetPlatform.TargetVersion == null)
                    TargetPlatform.TargetVersion = typeof(object).Module.Assembly.GetName().Version;
            }
            if (TargetPlatform.TargetVersion != null)
            {
                if (TargetPlatform.TargetVersion.Major > 1 || TargetPlatform.TargetVersion.Minor > 1 ||
                  (TargetPlatform.TargetVersion.Minor == 1 && TargetPlatform.TargetVersion.Build == 9999))
                {
                    if (SystemAssembly.IsValidTypeName(StandardIds.System, Identifier.For("Nullable`1")))
                        TargetPlatform.GenericTypeNamesMangleChar = '`';
                    else if (SystemAssembly.IsValidTypeName(StandardIds.System, Identifier.For("Nullable!1")))
                        TargetPlatform.GenericTypeNamesMangleChar = '!';
                    else if (TargetPlatform.TargetVersion.Major == 1 && TargetPlatform.TargetVersion.Minor == 2)
                        TargetPlatform.GenericTypeNamesMangleChar = (char)0;
                }
            }
            // This must be done in the order: Object, ValueType, Char, String
            // or else some of the generic type instantiations don't get filled
            // in correctly. (String ends up implementing IEnumerable<string>
            // instead of IEnumerable<char>.)
            Object = (Class)GetTypeNodeFor("System", "Object", ElementType.Object);
            ValueType = (Class)GetTypeNodeFor("System", "ValueType", ElementType.Class);
            Char = (Struct)GetTypeNodeFor("System", "Char", ElementType.Char);
            String = (Class)GetTypeNodeFor("System", "String", ElementType.String);
            Enum = (Class)GetTypeNodeFor("System", "Enum", ElementType.Class);
            MulticastDelegate = (Class)GetTypeNodeFor("System", "MulticastDelegate", ElementType.Class);
            Array = (Class)GetTypeNodeFor("System", "Array", ElementType.Class);
            Type = (Class)GetTypeNodeFor("System", "Type", ElementType.Class);
            Boolean = (Struct)GetTypeNodeFor("System", "Boolean", ElementType.Boolean);
            Int8 = (Struct)GetTypeNodeFor("System", "SByte", ElementType.Int8);
            UInt8 = (Struct)GetTypeNodeFor("System", "Byte", ElementType.UInt8);
            Int16 = (Struct)GetTypeNodeFor("System", "Int16", ElementType.Int16);
            UInt16 = (Struct)GetTypeNodeFor("System", "UInt16", ElementType.UInt16);
            Int32 = (Struct)GetTypeNodeFor("System", "Int32", ElementType.Int32);
            UInt32 = (Struct)GetTypeNodeFor("System", "UInt32", ElementType.UInt32);
            Int64 = (Struct)GetTypeNodeFor("System", "Int64", ElementType.Int64);
            UInt64 = (Struct)GetTypeNodeFor("System", "UInt64", ElementType.UInt64);
            Single = (Struct)GetTypeNodeFor("System", "Single", ElementType.Single);
            Double = (Struct)GetTypeNodeFor("System", "Double", ElementType.Double);
            IntPtr = (Struct)GetTypeNodeFor("System", "IntPtr", ElementType.IntPtr);
            UIntPtr = (Struct)GetTypeNodeFor("System", "UIntPtr", ElementType.UIntPtr);
            DynamicallyTypedReference = (Struct)GetTypeNodeFor("System", "TypedReference", ElementType.DynamicallyTypedReference);
            Delegate = (Class)GetTypeNodeFor("System", "Delegate", ElementType.Class);
            Exception = (Class)GetTypeNodeFor("System", "Exception", ElementType.Class);
            Attribute = (Class)GetTypeNodeFor("System", "Attribute", ElementType.Class);
            DBNull = (Class)GetTypeNodeFor("System", "DBNull", ElementType.Class);
            DateTime = (Struct)GetTypeNodeFor("System", "DateTime", ElementType.ValueType);
            Decimal = (Struct)GetTypeNodeFor("System", "Decimal", ElementType.ValueType);
            ArgIterator = (Struct)GetTypeNodeFor("System", "ArgIterator", ElementType.ValueType);
            IsVolatile = (Class)GetTypeNodeFor("System.Runtime.CompilerServices", "IsVolatile", ElementType.Class);
            Void = (Struct)GetTypeNodeFor("System", "Void", ElementType.Void);
            RuntimeFieldHandle = (Struct)GetTypeNodeFor("System", "RuntimeFieldHandle", ElementType.ValueType);
            RuntimeMethodHandle = (Struct)GetTypeNodeFor("System", "RuntimeMethodHandle", ElementType.ValueType);
            RuntimeTypeHandle = (Struct)GetTypeNodeFor("System", "RuntimeTypeHandle", ElementType.ValueType);
            RuntimeArgumentHandle = (Struct)GetTypeNodeFor("System", "RuntimeArgumentHandle", ElementType.ValueType);
            SecurityAction = GetTypeNodeFor("System.Security.Permissions", "SecurityAction", ElementType.ValueType) as EnumNode;
            CoreSystemTypes.Initialized = true;
            CoreSystemTypes.InstantiateGenericInterfaces();

            object dummy = TargetPlatform.AssemblyReferenceFor; //Force selection of target platform

            if(dummy == null)
                return;
        }
コード例 #8
0
ファイル: RewriteUtils.cs プロジェクト: nbulp/CodeContracts
 internal static void TryAddCompilerGeneratedAttribute(EnumNode Enum)
 {
   Contract.Requires(Enum != null);
     TryAddCompilerGeneratedAttribute(Enum, System.AttributeTargets.Enum);
 }
コード例 #9
0
        /// <summary>
        /// Creates a new instance of this class that contains the CCI nodes for contract class.
        /// </summary>
        /// <param name="errorHandler">Delegate receiving errors. If null, errors are thrown as exceptions.</param>
        ///
        private ContractNodes(AssemblyNode assembly, Action<System.CodeDom.Compiler.CompilerError> errorHandler)
        {
            if (errorHandler != null) this.ErrorFound += errorHandler;

            AssemblyNode assemblyContainingContractClass = null;

            // Get the contract class and all of its members

            assemblyContainingContractClass = assembly;
            ContractClass = assembly.GetType(ContractNamespace, Identifier.For("Contract")) as Class;
            if (ContractClass == null)
            {
                // This is not a candidate, no warning as we try to find the right place where contracts live
                return;
            }

            ContractHelperClass = assembly.GetType(ContractInternalNamespace, Identifier.For("ContractHelper")) as Class;
            if (ContractHelperClass == null || !ContractHelperClass.IsPublic)
            {
                // look in alternate location
                var alternateNs = Identifier.For("System.Diagnostics.Contracts.Internal");
                ContractHelperClass = assembly.GetType(alternateNs, Identifier.For("ContractHelper")) as Class;
            }

            // Get ContractFailureKind

            ContractFailureKind = assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("ContractFailureKind")) as EnumNode;

            // Look for each member of the contract class

            var requiresMethods = ContractClass.GetMethods(Identifier.For("Requires"), SystemTypes.Boolean);
            for (int i = 0; i < requiresMethods.Count; i++)
            {
                var method = requiresMethods[i];
                if (method.TemplateParameters != null && method.TemplateParameters.Count == 1)
                {
                    // Requires<E>
                    RequiresExceptionMethod = method;
                }
                else if (method.TemplateParameters == null || method.TemplateParameters.Count == 0)
                {
                    RequiresMethod = method;
                }
            }

            // early test to see if the ContractClass we found has a Requires(bool) method. If it doesn't, we 
            // silently think that this is not the right place.
            // We use this because contract reference assemblies have a Contract class, but it is not the right one, as it holds
            // just the 3 argument versions of all the contract methods.
            if (RequiresMethod == null)
            {
                ContractClass = null;
                return;
            }

            var requiresMethodsWithMsg = ContractClass.GetMethods(Identifier.For("Requires"), SystemTypes.Boolean, SystemTypes.String);
            for (int i = 0; i < requiresMethodsWithMsg.Count; i++)
            {
                var method = requiresMethodsWithMsg[i];
                if (method.TemplateParameters != null && method.TemplateParameters.Count == 1)
                {
                    // Requires<E>
                    RequiresExceptionWithMsgMethod = method;
                }

                else if (method.TemplateParameters == null || method.TemplateParameters.Count == 0)
                {
                    RequiresWithMsgMethod = method;
                }
            }

            EnsuresMethod = ContractClass.GetMethod(Identifier.For("Ensures"), SystemTypes.Boolean);
            
            EnsuresWithMsgMethod = ContractClass.GetMethod(Identifier.For("Ensures"), SystemTypes.Boolean, SystemTypes.String);
            EnsuresOnThrowTemplate = ContractClass.GetMethod(Identifier.For("EnsuresOnThrow"), SystemTypes.Boolean);
            EnsuresOnThrowWithMsgTemplate = ContractClass.GetMethod(Identifier.For("EnsuresOnThrow"), SystemTypes.Boolean, SystemTypes.String);

            InvariantMethod = ContractClass.GetMethod(Identifier.For("Invariant"), SystemTypes.Boolean);
            InvariantWithMsgMethod = ContractClass.GetMethod(Identifier.For("Invariant"), SystemTypes.Boolean, SystemTypes.String);

            AssertMethod = ContractClass.GetMethod(Identifier.For("Assert"), SystemTypes.Boolean);
            AssertWithMsgMethod = ContractClass.GetMethod(Identifier.For("Assert"), SystemTypes.Boolean, SystemTypes.String);

            AssumeMethod = ContractClass.GetMethod(Identifier.For("Assume"), SystemTypes.Boolean);
            AssumeWithMsgMethod = ContractClass.GetMethod(Identifier.For("Assume"), SystemTypes.Boolean, SystemTypes.String);

            ResultTemplate = ContractClass.GetMethod(ResultName);

            TypeNode GenericPredicate = SystemTypes.SystemAssembly.GetType(
                Identifier.For("System"),
                Identifier.For("Predicate" + TargetPlatform.GenericTypeNamesMangleChar + "1"));

            if (GenericPredicate != null)
            {
                ForAllGenericTemplate = ContractClass.GetMethod(ForallName, SystemTypes.GenericIEnumerable, GenericPredicate);
                ExistsGenericTemplate = ContractClass.GetMethod(ExistsName, SystemTypes.GenericIEnumerable, GenericPredicate);

                if (ForAllGenericTemplate == null)
                {
                    // The problem might be that we are in the pre 4.0 scenario and using an out-of-band contract for mscorlib
                    // in which case the contract library is defined in that out-of-band contract assembly.
                    // If so, then ForAll and Exists are defined in terms of the System.Predicate defined in the out-of-band assembly.
                    var tempGenericPredicate = assemblyContainingContractClass.GetType(
                        Identifier.For("System"),
                        Identifier.For("Predicate" + TargetPlatform.GenericTypeNamesMangleChar + "1"));

                    if (tempGenericPredicate != null)
                    {
                        GenericPredicate = tempGenericPredicate;
                        TypeNode genericIEnum =
                            assemblyContainingContractClass.GetType(Identifier.For("System.Collections.Generic"),
                                Identifier.For("IEnumerable" + TargetPlatform.GenericTypeNamesMangleChar + "1"));

                        ForAllGenericTemplate = ContractClass.GetMethod(Identifier.For("ForAll"), genericIEnum, GenericPredicate);
                        ExistsGenericTemplate = ContractClass.GetMethod(Identifier.For("Exists"), genericIEnum, GenericPredicate);
                    }
                }

                TypeNode PredicateOfInt = GenericPredicate.GetTemplateInstance(ContractClass, SystemTypes.Int32);
                if (PredicateOfInt != null)
                {
                    ForAllTemplate = ContractClass.GetMethod(Identifier.For("ForAll"), SystemTypes.Int32, SystemTypes.Int32, PredicateOfInt);
                    ExistsTemplate = ContractClass.GetMethod(Identifier.For("Exists"), SystemTypes.Int32, SystemTypes.Int32, PredicateOfInt);
                }
            }

            foreach (Member member in ContractClass.GetMembersNamed(ValueAtReturnName))
            {
                Method method = member as Method;
                if (method != null && method.Parameters.Count == 1)
                {
                    Reference reference = method.Parameters[0].Type as Reference;
                    if (reference != null && reference.ElementType.IsTemplateParameter)
                    {
                        ParameterTemplate = method;
                        break;
                    }
                }
            }

            foreach (Member member in ContractClass.GetMembersNamed(OldName))
            {
                Method method = member as Method;
                if (method != null && method.Parameters.Count == 1 && method.Parameters[0].Type.IsTemplateParameter)
                {
                    OldTemplate = method;
                    break;
                }
            }

            EndContract = ContractClass.GetMethod(Identifier.For("EndContractBlock"));
            if (this.ContractFailureKind != null)
            {
                if (ContractHelperClass != null)
                {
                    RaiseFailedEventMethod = ContractHelperClass.GetMethod(ContractNodes.RaiseContractFailedEventName,
                        this.ContractFailureKind, SystemTypes.String, SystemTypes.String, SystemTypes.Exception);

                    TriggerFailureMethod = ContractHelperClass.GetMethod(ContractNodes.TriggerFailureName,
                        this.ContractFailureKind, SystemTypes.String, SystemTypes.String, SystemTypes.String, SystemTypes.Exception);
                }
            }

            // Get the attributes

            PureAttribute = assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("PureAttribute")) as Class;
            InvariantMethodAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("ContractInvariantMethodAttribute")) as Class;

            ContractClassAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, ContractClassAttributeName) as Class;

            ContractClassForAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, ContractClassForAttributeName) as Class;

            VerifyAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("ContractVerificationAttribute")) as Class;
            SpecPublicAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, SpecPublicAttributeName) as Class;

            ReferenceAssemblyAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("ContractReferenceAssemblyAttribute")) as Class;
            IgnoreAtRuntimeAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, RuntimeIgnoredAttributeName) as Class;

            // Check that every field in this class has been set

            foreach (System.Reflection.FieldInfo field in typeof (ContractNodes).GetFields())
            {
                if (field.GetValue(this) == null)
                {
                    string sig = null;
                    bool required = false;

                    object[] cas = field.GetCustomAttributes(typeof (RepresentationFor), false);
                    for (int i = 0, n = cas.Length; i < n; i++)
                    {
                        // should be exactly one
                        RepresentationFor rf = cas[i] as RepresentationFor;
                        if (rf != null)
                        {
                            sig = rf.runtimeName;
                            required = rf.required;
                            break;
                        }
                    }

                    if (!required) continue;
                    
                    string msg = "Could not find contract node for '" + field.Name + "'";
                    if (sig != null)
                        msg = "Could not find the method/type '" + sig + "'";

                    if (ContractClass != null && ContractClass.DeclaringModule != null)
                    {
                        msg += " in assembly '" + ContractClass.DeclaringModule.Location + "'";
                    }

                    Module dm = ContractClass.DeclaringModule;
                    
                    ClearFields();
                    CallErrorFound(dm, msg);
                    
                    return;
                }
            }

            // Check that ContractFailureKind is okay

            if (this.ContractFailureKind.GetField(Identifier.For("Assert")) == null
                || this.ContractFailureKind.GetField(Identifier.For("Assume")) == null
                || this.ContractFailureKind.GetField(Identifier.For("Invariant")) == null
                || this.ContractFailureKind.GetField(Identifier.For("Postcondition")) == null
                || this.ContractFailureKind.GetField(Identifier.For("Precondition")) == null
                )
            {
                Module dm = ContractClass.DeclaringModule;
                
                ClearFields();
                CallErrorFound(dm, "The enum ContractFailureKind must have the values 'Assert', 'Assume', 'Invariant', 'Postcondition', and 'Precondition'.");
            }
        }
コード例 #10
0
ファイル: Parser.cs プロジェクト: dbremner/specsharp
 private void ParseEnumDeclaration(Namespace ns, TypeNode parentType, AttributeList attributes, TokenList modifierTokens,
   SourceContextList modifierContexts, TypeFlags flags, SourceContext sctx, TokenSet followers){
   EnumNode e = new EnumNode();
   e.Attributes = attributes;
   if (parentType == null)
     e.DeclaringNamespace = ns;
   else{
     e.DeclaringType = parentType;
     e.IsGeneric = parentType.IsGeneric;
   }
   if (modifierTokens != null)
     e.Flags |= this.NestedTypeFlags(modifierTokens, modifierContexts, e)|TypeFlags.Sealed;
   else{
     if ((flags & TypeFlags.Abstract) != 0){
       if ((flags & TypeFlags.Sealed) != 0 && (flags & TypeFlags.SpecialName) != 0){
         this.HandleError(Error.InvalidModifier, "static");
         flags &= ~(TypeFlags.Abstract|TypeFlags.Sealed|TypeFlags.SpecialName);
       }else{
         this.HandleError(Error.InvalidModifier, "abstract");
         flags &= ~TypeFlags.Abstract;
       }
     }else if ((flags & TypeFlags.Sealed) != 0){
       this.HandleError(Error.InvalidModifier, "sealed");
       flags &= ~TypeFlags.Sealed;
     }
     e.Flags |= flags|TypeFlags.Sealed;
     e.IsUnsafe = this.inUnsafeCode;
   }
   e.SourceContext = sctx;
   e.DeclaringModule = this.module;
   Debug.Assert(this.currentToken == Token.Enum);
   this.GetNextToken();
   e.Name = this.scanner.GetIdentifier();
   this.SkipIdentifierOrNonReservedKeyword();
   if (parentType != null){
     e.Namespace = Identifier.Empty;
     parentType.Members.Add(e);
   }else{
     e.Namespace = ns.FullNameId;
     ns.Types.Add(e);
     this.AddTypeToModule(e);
     if (this.inUnsafeCode) this.HandleError(e.Name.SourceContext, Error.InvalidModifier, "unsafe");
   }
   TypeNode t = this.TypeExpressionFor(Token.Int);
   if (this.currentToken == Token.Colon){
     this.GetNextToken();
     switch(this.currentToken){
       case Token.Sbyte:
       case Token.Byte:
       case Token.Short:
       case Token.Ushort:
       case Token.Int:
       case Token.Uint:
       case Token.Long:
       case Token.Ulong:
         t = this.TypeExpressionFor(this.currentToken);
         this.GetNextToken();
         break;
       default:
         TypeNode tt = this.ParseTypeExpression(null, followers|Token.LeftBrace);
         if (tt != null)
           this.HandleError(tt.SourceContext, Error.IntegralTypeExpected);
         break;
     }
   }
   e.UnderlyingTypeExpression = t;
   e.SourceContext.EndPos = this.scanner.endPos;
   e.Documentation = this.LastDocComment;
   SourceContext typeBodyCtx = this.scanner.CurrentSourceContext;
   this.Skip(Token.LeftBrace);
   Field prevField = null;
   int offset = 0;
   while (this.currentToken != Token.RightBrace){
     if (this.currentToken == Token.SingleLineDocCommentStart || this.currentToken == Token.MultiLineDocCommentStart)
       this.ParseDocComment(followers|Parser.IdentifierOrNonReservedKeyword|Token.Comma|Token.RightBrace);
     SourceContext ctx = this.scanner.CurrentSourceContext;
     AttributeList attrs = this.ParseAttributes(null, followers|Parser.IdentifierOrNonReservedKeyword|Token.Comma|Token.RightBrace);
     Identifier id = this.scanner.GetIdentifier();
     this.SkipIdentifierOrNonReservedKeyword();
     Field f = new Field(e, attrs, FieldFlags.Public|FieldFlags.Literal|FieldFlags.Static|FieldFlags.HasDefault, id, e, null);
     e.Members.Add(f);
     f.Documentation = this.LastDocComment;
     f.SourceContext = ctx;
     if (this.currentToken == Token.Assign){
       this.GetNextToken();
       if (Parser.UnaryStart[this.currentToken])
         f.Initializer = this.ParseExpression(followers|Token.Comma|Token.RightBrace);
       else{
         this.SkipTo(followers|Token.Comma|Token.RightBrace, Error.ConstantExpected);
         f.Initializer = new Literal(offset++);
       }
       prevField = f;
     }else{
       if (prevField == null)
         f.Initializer = new Literal(offset++);
       else{
         f.Initializer = new BinaryExpression(new MemberBinding(null, prevField), new Literal(1), NodeType.Add, ctx);
         prevField = f;
       }
     }
     if (this.currentToken != Token.Comma){
       if (this.currentToken == Token.Semicolon){
         SourceContext sc = this.scanner.CurrentSourceContext;
         this.GetNextToken();
         if (Parser.IdentifierOrNonReservedKeyword[this.currentToken]){
           this.HandleError(sc, Error.SyntaxError, ",");
           continue;
         }else if (this.currentToken == Token.RightBrace){
           this.HandleError(sc, Error.ExpectedRightBrace);
           break;
         }
       }
       break;
     }
     this.GetNextToken();
   }
   int endCol = this.scanner.endPos;
   if (this.sink != null){
     typeBodyCtx.EndPos = this.scanner.endPos;
     this.sink.AddCollapsibleRegion(typeBodyCtx, false);
   }
   this.ParseBracket(e.SourceContext, Token.RightBrace, followers|Token.Semicolon, Error.ExpectedRightBrace);
   e.SourceContext.EndPos = endCol;
   if (this.currentToken == Token.Semicolon)
     this.GetNextToken();
   this.SkipTo(followers|Parser.TypeMemberStart);
   if (!followers[this.currentToken])
     this.SkipTo(followers, Error.NamespaceUnexpected);
 }
コード例 #11
0
ファイル: MRefWriter.cs プロジェクト: armin-bauer/SHFB
        /// <summary>
        /// Get an enumerable list of applied fields from an enumeration type
        /// </summary>
        /// <param name="enumeration">The enumeration from which to get the fields</param>
        /// <param name="value">The value to use in determining the applied fields</param>
        /// <returns>An enumerable list of fields from the enumeration that appear in the value</returns>
        private static IEnumerable<Field> GetAppliedFields(EnumNode enumeration, long value)
        {
            FieldList list = new FieldList();
            MemberList members = enumeration.Members;

            foreach(var member in members)
            {
                if(member.NodeType != NodeType.Field)
                    continue;

                Field field = (Field)member;

                if(field.DefaultValue != null)
                {
                    long fieldValue = Convert.ToInt64(field.DefaultValue.Value, CultureInfo.InvariantCulture);

                    // If a single field matches, return it.  Otherwise return all fields that are in value.
                    if(fieldValue == value)
                        return new[] { field };

                    if((fieldValue & value) == fieldValue)
                        list.Add(field);
                }
            }

            return list;
        }
コード例 #12
0
ファイル: Splicer.cs プロジェクト: ZingModelChecker/Zing
        private void GenerateEnum(EnumNode enumNode)
        {
            // Make the enum type "internal" in the generated code.
            enumNode.Flags |= TypeFlags.NotPublic;
            enumNode.Flags &= ~TypeFlags.Public;
            InstallType(enumNode);

            TypeNode enumClass = Templates.GetTypeTemplateByName("Enum");

            Debug.Assert(enumClass.Members[0] is Field);
            Field f = (Field)enumClass.Members[0];
            f.Name = new Identifier(enumNode.Name.Name + "Choices");

            choosableTypes.Add(enumNode.Name, f.Name);

            Debug.Assert(f.Initializer != null && f.Initializer is ConstructArray);
            ConstructArray consArray = (ConstructArray)f.Initializer;
            for (int i = 1, n = enumNode.Members.Count; i < n; i++)
                consArray.Initializers.Add(new QualifiedIdentifier(enumNode.Name, enumNode.Members[i].Name));

            appClass.Members.Add(f);
            f.DeclaringType = appClass;
        }
コード例 #13
0
ファイル: Decompiler.cs プロジェクト: ZingModelChecker/Zing
        public override EnumNode VisitEnumNode(EnumNode enumNode)
        {
            WriteStart("{0}enum ", GetTypeQualifiers(enumNode));
            this.VisitIdentifier(enumNode.Name);
            Write(" : ");
            this.VisitTypeReference(enumNode.UnderlyingType);
            WriteFinish(string.Empty);
            WriteLine("{");
            In();
            for (int i = 0, n = enumNode.Members.Count; i < n; i++)
            {
                Field field = (Field)enumNode.Members[i];

                if (!field.IsSpecialName)
                {
                    WriteStart(string.Empty);
                    this.VisitIdentifier(field.Name);
                    if (field.Initializer != null)
                    {
                        Write(" = ");
                        this.VisitExpression(field.Initializer);
                    }
                    WriteFinish(",");
                }
            }
            Out();
            WriteLine("};");
            return enumNode;
        }
コード例 #14
0
ファイル: Rewriter.cs プロジェクト: nbulp/CodeContracts
 private static void AddEnumValue(EnumNode enumType, string name, object value)
 {
   var enumValue = new Field(enumType, null, FieldFlags.Assembly | FieldFlags.HasDefault | FieldFlags.Literal | FieldFlags.Static, Identifier.For(name), enumType, new Literal(value, SystemTypes.Int32));
   enumType.Members.Add(enumValue);
 }
コード例 #15
0
ファイル: SystemTypes.cs プロジェクト: armin-bauer/SHFB
        private static void ClearStatics()
        {
            //Special base types
            Object = null;
            String = null;
            ValueType = null;
            Enum = null;
            MulticastDelegate = null;
            Array = null;
            Type = null;
            Delegate = null;
            Exception = null;
            Attribute = null;

            //primitive types
            Boolean = null;
            Char = null;
            Int8 = null;
            UInt8 = null;
            Int16 = null;
            UInt16 = null;
            Int32 = null;
            UInt32 = null;
            Int64 = null;
            UInt64 = null;
            Single = null;
            Double = null;
            IntPtr = null;
            UIntPtr = null;
            DynamicallyTypedReference = null;

            //Special types
            DBNull = null;
            DateTime = null;
            Decimal = null;
            RuntimeArgumentHandle = null;
            ArgIterator = null;
            RuntimeFieldHandle = null;
            RuntimeMethodHandle = null;
            RuntimeTypeHandle = null;
            IsVolatile = null;
            Void = null;
            SecurityAction = null;
        }
コード例 #16
0
 public virtual EnumNode VisitEnumNode(EnumNode enumNode)
 {
     return (EnumNode)this.VisitTypeNode(enumNode);
 }
コード例 #17
0
ファイル: SystemTypes.cs プロジェクト: armin-bauer/SHFB
 internal static TypeNode/*!*/ GetDummyTypeNode(AssemblyNode declaringAssembly, string/*!*/ nspace, string/*!*/ name, ElementType typeCode)
 {
     TypeNode result = null;
     switch (typeCode)
     {
         case ElementType.Object:
         case ElementType.String:
         case ElementType.Class:
             if (name.Length > 1 && name[0] == 'I' && char.IsUpper(name[1]))
                 result = new Interface();
             else if (name == "MulticastDelegate" || name == "Delegate")
                 result = new Class();
             else if (name.EndsWith("Callback") || name.EndsWith("Delegate") || name == "ThreadStart" || name == "FrameGuardGetter" || name == "GuardThreadStart")
                 result = new DelegateNode();
             else
                 result = new Class();
             break;
         default:
             if (name == "CciMemberKind")
                 result = new EnumNode();
             else
                 result = new Struct();
             break;
     }
     result.Name = Identifier.For(name);
     result.Namespace = Identifier.For(nspace);
     result.DeclaringModule = declaringAssembly;
     return result;
 }
コード例 #18
0
ファイル: ZDecompiler.cs プロジェクト: ZingModelChecker/Zing
        public override EnumNode VisitEnumNode(EnumNode enumNode)
        {
            WriteStart("enum {0}", enumNode.Name.Name);

            if (this.braceOnNewLine)
            {
                WriteFinish(string.Empty);
                WriteLine("{");
            }
            else
                WriteFinish(" {");

            In();
            for (int i = 0, n = enumNode.Members.Count; i < n; i++)
            {
                Field field = (Field)enumNode.Members[i];

                if (!field.IsSpecialName)
                {
                    WriteStart(field.Name.Name);
                    WriteFinish(",");
                }
            }
            Out();
            WriteLine("};");
            return enumNode;
        }
コード例 #19
0
 public EventingVisitor(Action<EnumNode> visitEnumNode) { VisitedEnumNode += visitEnumNode; } public event Action<EnumNode> VisitedEnumNode; public override EnumNode VisitEnumNode(EnumNode enumNode) { if (VisitedEnumNode != null) VisitedEnumNode(enumNode); return base.VisitEnumNode(enumNode); }