public MetadataGenerationError(MetadataType metadataType, Type type, string errorReason, string sugestionedSolution)
 {
     MetadataType = metadataType;
     Type = type;
     ErrorReason = errorReason;
     SuggestedSolution = sugestionedSolution;
 }
예제 #2
0
 public MetadataCheckBox(MetadataType metadataType, string displayText, string count, string ignoredCount)
     : this(metadataType, displayText, count)
 {
     lblIgnoredFields.Text = "( Excluded " + ignoredCount + " fields )";
     lblIgnoredFields.Visible = true;
     MetadataType = metadataType;
 }
예제 #3
0
        /// <summary>
        /// PeerEventArgs Constructor
        /// </summary>
        /// <param name="parsed">a simple MessageParse</param>
        internal PeerEventArgs(dynamic parsed)
        {
#if DEBUG
            FCP2Protocol.ArgsDebug(this, parsed);
#endif

            lastGoodVersion = parsed.lastGoodVersion;
            opennet = parsed.opennet;
            myName = parsed.myName;
            identity = parsed.identity;
            location = parsed.location;
            testnet = parsed.testnet;
            version = parsed.version;
            physical = new PhysicalType(parsed);
            ark = new ArkType(parsed);
            dsaPubKey = new DsaPubKeyType(parsed);
            dsaGroup = new DsaGroupType(parsed);
            auth = new AuthType(parsed);
            @volatile = new VolatileType(parsed);
            metadata = new MetadataType(parsed);

#if DEBUG
            parsed.PrintAccessCount();
#endif
        }
예제 #4
0
        /// <summary>
        /// PeerEventArgs Constructor
        /// </summary>
        /// <param name="parsed">a simple MessageParse</param>
        internal PeerEventArgs(dynamic parsed)
        {
#if DEBUG
            FCP2Protocol.ArgsDebug(this, parsed);
#endif

            LastGoodVersion = parsed.lastGoodVersion;
            Opennet = parsed.opennet;
            MyName = parsed.myName;
            Identity = parsed.identity;
            Location = parsed.location;
            Testnet = parsed.testnet;
            Version = parsed.version;
            Physical = new PhysicalType(parsed);
            Ark = new ArkType(parsed);
            DsaPubKey = new DsaPubKeyType(parsed);
            DsaGroup = new DsaGroupType(parsed);
            Auth = new AuthType(parsed);
            Volatile = new VolatileType(parsed);
            Metadata = new MetadataType(parsed);

#if DEBUG
            parsed.PrintAccessCount();
#endif
        }
예제 #5
0
 public static void GetTableName(MetadataType type, out string tableName, out string keyFieldName)
 {
     tableName = string.Empty;
     keyFieldName = "Id";
     switch (type)
     {
         case MetadataType.QuotationSource:
             tableName = "QuotationSource";
             break;
         case MetadataType.Instrument:
             tableName = "Instrument";
             break;
         case MetadataType.InstrumentSourceRelation:
             tableName = "InstrumentSourceRelation";
             break;
         case MetadataType.DerivativeRelation:
             tableName = "DerivativeRelation";
             keyFieldName = "InstrumentId";
             break;
         case MetadataType.PriceRangeCheckRule:
             tableName = "PriceRangeCheckRule";
             keyFieldName = "InstrumentId";
             break;
         case MetadataType.WeightedPriceRule:
             tableName = "WeightedPriceRule";
             keyFieldName = "InstrumentId";
             break;
     }
 }
예제 #6
0
        public override IEnumerable<string> GetMetadata(MetadataType type)
        {
            if (parsedFile.Metadata.ContainsKey(type))
                return parsedFile.Metadata[type];

            return null;
        }
예제 #7
0
        public static  bool IsSupportedRiskElements(FileType fileType, MetadataType metadatatype)
        {
            if (metadatatype == MetadataType.Hyperlink && OptionApi.GetBool(SharedRibbon.Library.Options.ExcludeFieldCodesHyperlinks))
                return false;

            if (IsExcel(fileType))
            {
                switch (metadatatype)
                {
                    case MetadataType.SmallText:
                    case MetadataType.WhiteText:
                    case MetadataType.HiddenText:
                        return false;
                    default:
                        return true;
                }
            }

            if (IsWord(fileType))
            {
                switch (metadatatype)
                {
                    case MetadataType.Hyperlink:
                    {
                        return false;
                    }
                }
            }

            return true;
        }
		internal MetadataPropertyInfo (IMetadataImport importer, int propertyToken, MetadataType declaringType)
		{
			m_importer = importer;
			m_propertyToken = propertyToken;
			m_declaringType = declaringType;

			int mdTypeDef;
			int pchProperty;
			int pdwPropFlags;
			IntPtr ppvSig;
			int pbSig;
			int pdwCPlusTypeFlag;
			IntPtr ppDefaultValue;
			int pcchDefaultValue;
			int rmdOtherMethod;
			int pcOtherMethod;

			m_importer.GetPropertyProps (
				m_propertyToken,
				out mdTypeDef,
				null,
				0,
				out pchProperty,
				out pdwPropFlags,
				out ppvSig,
				out pbSig,
				out pdwCPlusTypeFlag,
				out ppDefaultValue,
				out pcchDefaultValue,
				out m_pmdSetter,
				out m_pmdGetter,
				out rmdOtherMethod,
				0,
				out pcOtherMethod);

			StringBuilder szProperty = new StringBuilder (pchProperty);
			m_importer.GetPropertyProps (
				m_propertyToken,
				out mdTypeDef,
				szProperty,
				pchProperty,
				out pchProperty,
				out pdwPropFlags,
				out ppvSig,
				out pbSig,
				out pdwCPlusTypeFlag,
				out ppDefaultValue,
				out pcchDefaultValue,
				out m_pmdSetter,
				out m_pmdGetter,
				out rmdOtherMethod,
				0,
				out pcOtherMethod);

			m_propAttributes = (PropertyAttributes) pdwPropFlags;
			m_name = szProperty.ToString ();
			MetadataHelperFunctions.GetCustomAttribute (importer, propertyToken, typeof (System.Diagnostics.DebuggerBrowsableAttribute));
		}
예제 #9
0
        public static string GetParamType(this MetadataPropertyType prop, MetadataType type, Operation op)
        {
            if (prop.ParamType != null)
                return prop.ParamType;

            var isRequest = type.Name == op.RequestType.Name;

            return !isRequest ? "form" : GetRequestParamType(op, prop.Name);
        }
예제 #10
0
        private static object ParseDefaultValue(MetadataType declaringType, IntPtr ppvSigBlob, IntPtr ppvRawValue)
        {
                IntPtr ppvSigTemp = ppvSigBlob;
                CorCallingConvention callingConv = MetadataHelperFunctions.CorSigUncompressCallingConv(ref ppvSigTemp);
                Debug.Assert(callingConv == CorCallingConvention.Field);

                CorElementType elementType = MetadataHelperFunctions.CorSigUncompressElementType(ref ppvSigTemp);
                if (elementType == CorElementType.ELEMENT_TYPE_VALUETYPE)
                {
                        uint token = MetadataHelperFunctions.CorSigUncompressToken(ref ppvSigTemp);

                        if (token == declaringType.MetadataToken)
                        {
                            // Static literal field of the same type as the enclosing type
                            // may be one of the value fields of an enum
                            if (declaringType.ReallyIsEnum)
                            {
                                // If so, the value will be of the enum's underlying type,
                                // so we change it from VALUETYPE to be that type so that
                                // the following code will get the value
                                elementType = declaringType.EnumUnderlyingType;
                            }                           
                        }
                }
                
                switch (elementType)
                {
                    case CorElementType.ELEMENT_TYPE_CHAR:
                        return (char)Marshal.ReadByte(ppvRawValue);
                    case CorElementType.ELEMENT_TYPE_I1:
                        return (sbyte)Marshal.ReadByte(ppvRawValue);
                    case CorElementType.ELEMENT_TYPE_U1:
                        return Marshal.ReadByte(ppvRawValue);
                    case CorElementType.ELEMENT_TYPE_I2:
                        return Marshal.ReadInt16(ppvRawValue);
                    case CorElementType.ELEMENT_TYPE_U2:
                        return (ushort)Marshal.ReadInt16(ppvRawValue);
                    case CorElementType.ELEMENT_TYPE_I4:
                        return Marshal.ReadInt32(ppvRawValue);
                    case CorElementType.ELEMENT_TYPE_U4:
                        return (uint)Marshal.ReadInt32(ppvRawValue);
                    case CorElementType.ELEMENT_TYPE_I8:
                        return Marshal.ReadInt64(ppvRawValue);
                    case CorElementType.ELEMENT_TYPE_U8:
                        return (ulong)Marshal.ReadInt64(ppvRawValue);
                    case CorElementType.ELEMENT_TYPE_I:
                        return Marshal.ReadIntPtr(ppvRawValue);
                    case CorElementType.ELEMENT_TYPE_U:
                    case CorElementType.ELEMENT_TYPE_R4:
                    case CorElementType.ELEMENT_TYPE_R8:
                    // Technically U and the floating-point ones are options in the CLI, but not in the CLS or C#, so these are NYI
                    default:
                        return null;
                }
        }
        internal static MetadataField makeMetadataField(string description, string name, MetadataType type, int pos, string format, Guid guid)
        {
            MetadataField metadataField = new MetadataField();
            metadataField.Description = description;
            metadataField.Name = name;
            metadataField.Type = type;
            metadataField.Guid = guid;
            metadataField.DisplayPosition = pos;
            metadataField.DisplayFormat = format;

            return metadataField;
        }
예제 #12
0
        public void AddProperties(StringBuilderWrapper sb, MetadataType type, bool includeResponseStatus)
        {
            var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;

            var wasAdded = false;

            var dataMemberIndex = 1;
            if (type.Properties != null)
            {
                foreach (var prop in type.Properties)
                {
                    if (wasAdded) sb.AppendLine();

                    var propType = Type(prop.Type, prop.GenericArgs);
                    wasAdded = AppendComments(sb, prop.Description);
                    wasAdded = AppendDataMember(sb, prop.DataMember, dataMemberIndex++) || wasAdded;
                    wasAdded = AppendAttributes(sb, prop.Attributes) || wasAdded;

                    if (!type.IsInterface())
                    {
                        sb.AppendLine("member val {1}:{0} = {2} with get,set".Fmt(
                            propType, prop.Name.SafeToken(), GetDefaultLiteral(prop, type)));
                    }
                    else
                    {
                        sb.AppendLine("abstract {1}:{0} with get,set".Fmt(
                            propType, prop.Name.SafeToken()));
                    }
                }
            }

            if (type.IsInterface())
                return;

            if (includeResponseStatus)
            {
                if (wasAdded) sb.AppendLine();
                wasAdded = true;

                AppendDataMember(sb, null, dataMemberIndex++);
                sb.AppendLine("member val ResponseStatus:ResponseStatus = null with get,set");
            }

            if (makeExtensible
                && (type.Properties == null
                    || type.Properties.All(x => x.Name != "ExtensionData")))
            {
                if (wasAdded) sb.AppendLine();
                wasAdded = true;

                sb.AppendLine("member val ExtensionData:ExtensionDataObject = null with get,set");
            }
        }
        /// <summary>
        /// ExpectedMIMEEventArgs Constructor
        /// </summary>
        /// <param name="parsed">a simple MessageParse</param>
        internal ExpectedMimeEventArgs(dynamic parsed)
        {
#if DEBUG
            FCP2Protocol.ArgsDebug(this, parsed);
#endif
            identifier = parsed.identifier;
            global = parsed.global;
            metadata = new MetadataType(parsed);

#if DEBUG
            parsed.PrintAccessCount();
#endif
        }
예제 #14
0
 public void SubmitChange(MetadataType metadataType, string filed, object value)
 {
     ConsoleClient.Instance.UpdateMetadataObjectField(metadataType, this._MetadataObject.Id, filed, value, delegate(bool success)
     {
         if (success)
         {
             this.ApplyChangeToUI(filed, value);
         }
         else
         {
             base.OnPropertyChanged(filed);
         }
     });
 }
예제 #15
0
        public void AddProperties(StringBuilderWrapper sb, MetadataType type, bool includeResponseStatus)
        {
            var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;

            var @virtual = Config.MakeVirtual && !type.IsInterface() ? "Overridable " : "";
            var wasAdded = false;

            var dataMemberIndex = 1;
            if (type.Properties != null)
            {
                foreach (var prop in type.Properties)
                {
                    if (wasAdded) sb.AppendLine();

                    var propType = Type(prop.Type, prop.GenericArgs, includeNested:true);
                    wasAdded = AppendComments(sb, prop.Description);
                    wasAdded = AppendDataMember(sb, prop.DataMember, dataMemberIndex++) || wasAdded;
                    wasAdded = AppendAttributes(sb, prop.Attributes) || wasAdded;
                    var visibility = type.IsInterface() ? "" : "Public ";
                    sb.AppendLine("{0}{1}Property {2} As {3}".Fmt(
                        visibility,
                        @virtual,
                        EscapeKeyword(prop.Name).SafeToken(),
                        propType));
                }
            }

            if (type.IsInterface())
                return;

            if (includeResponseStatus)
            {
                if (wasAdded) sb.AppendLine();
                wasAdded = true;

                wasAdded = AppendDataMember(sb, null, dataMemberIndex++);
                sb.AppendLine("Public {0}Property ResponseStatus As ResponseStatus".Fmt(@virtual));
            }

            if (makeExtensible
                && (type.Properties == null
                    || type.Properties.All(x => x.Name != "ExtensionData")))
            {
                if (wasAdded) sb.AppendLine();
                wasAdded = true;

                sb.AppendLine("Public {0}Property ExtensionData As ExtensionDataObject Implements IExtensibleDataObject.ExtensionData".Fmt(@virtual));
            }
        }
예제 #16
0
        internal MetadataFieldInfo(IMetadataImport importer,int fieldToken, MetadataType declaringType)
        {
            m_importer = importer;
            m_fieldToken = fieldToken;
            m_declaringType = declaringType;

            // Initialize
            int mdTypeDef;
            int pchField,pcbSigBlob,pdwCPlusTypeFlab,pcchValue, pdwAttr;
            IntPtr ppvSigBlob;
            IntPtr ppvRawValue;
            m_importer.GetFieldProps(m_fieldToken,
                                     out mdTypeDef,
                                     null,
                                     0,
                                     out pchField,
                                     out pdwAttr,
                                     out ppvSigBlob,
                                     out pcbSigBlob,
                                     out pdwCPlusTypeFlab,
                                     out ppvRawValue,
                                     out pcchValue
                                     );
            
            StringBuilder szField = new StringBuilder(pchField);
            m_importer.GetFieldProps(m_fieldToken,
                                     out mdTypeDef,
                                     szField,
                                     szField.Capacity,
                                     out pchField,
                                     out pdwAttr,
                                     out ppvSigBlob,
                                     out pcbSigBlob,
                                     out pdwCPlusTypeFlab,
                                     out ppvRawValue,
                                     out pcchValue
                                     );
            m_fieldAttributes = (FieldAttributes)pdwAttr;
            m_name = szField.ToString();

            // Get the values for static literal fields with primitive types
            FieldAttributes staticLiteralField = FieldAttributes.Static | FieldAttributes.HasDefault | FieldAttributes.Literal;
            if ((m_fieldAttributes & staticLiteralField) == staticLiteralField)
            {
                m_value = ParseDefaultValue(declaringType,ppvSigBlob,ppvRawValue);
            }
			// [Xamarin] Expression evaluator.
			MetadataHelperFunctions.GetCustomAttribute (importer, m_fieldToken, typeof (System.Diagnostics.DebuggerBrowsableAttribute));
		}
        internal MetadataFieldInfo(IMetadataImport importer, int fieldToken, MetadataType declaringType)
        {
            m_importer = importer;
            m_fieldToken = fieldToken;
            m_declaringType = declaringType;

            // Initialize
            int mdTypeDef;
            int pchField, pcbSigBlob, pdwCPlusTypeFlab, pcchValue, pdwAttr;
            IntPtr ppvSigBlob;
            IntPtr ppvRawValue;
            m_importer.GetFieldProps(m_fieldToken,
                                     out mdTypeDef,
                                     null,
                                     0,
                                     out pchField,
                                     out pdwAttr,
                                     out ppvSigBlob,
                                     out pcbSigBlob,
                                     out pdwCPlusTypeFlab,
                                     out ppvRawValue,
                                     out pcchValue
                );

            var szField = new StringBuilder(pchField);
            m_importer.GetFieldProps(m_fieldToken,
                                     out mdTypeDef,
                                     szField,
                                     szField.Capacity,
                                     out pchField,
                                     out pdwAttr,
                                     out ppvSigBlob,
                                     out pcbSigBlob,
                                     out pdwCPlusTypeFlab,
                                     out ppvRawValue,
                                     out pcchValue
                );
            m_fieldAttributes = (FieldAttributes) pdwAttr;
            m_name = szField.ToString();

            // Get the values for static literal fields with primitive types
            FieldAttributes staticLiteralField = FieldAttributes.Static | FieldAttributes.HasDefault |
                                                 FieldAttributes.Literal;
            if ((m_fieldAttributes & staticLiteralField) == staticLiteralField)
            {
                m_value = ParseDefaultValue(declaringType, ppvSigBlob, ppvRawValue);
            }
        }
        public ExtendedQueryParameters()
        {
            // Default all parameters
            QuerySchemas = new string[]{};
            MetaQueryValues = new List<MetaQueryItem>();
            MetaQueryLogic = QueryLogic.AllCriteriaMatch;

            KeywordValues = new List<KeywordItem>();
            KeywordQueryLogic = QueryLogic.AllCriteriaMatch;

            LastPublishedDate = DateTime.MinValue;

            QuerySortField = "ItemTitle";
            SortType = MetadataType.STRING;
            QuerySortOrder = MetaQueryOrder.Ascending;
            MaximumComponents = int.MaxValue;
        }
예제 #19
0
        public void AddProperties(StringBuilderWrapper sb, MetadataType type)
        {
            var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;

            var @virtual = Config.MakeVirtual ? "virtual " : "";
            var wasAdded = false;

            var dataMemberIndex = 1;
            if (type.Properties != null)
            {
                foreach (var prop in type.Properties)
                {
                    if (wasAdded) sb.AppendLine();

                    var propType = Type(prop.Type, prop.GenericArgs);
                    wasAdded = AppendDataMember(sb, prop.DataMember, dataMemberIndex++);
                    wasAdded = AppendAttributes(sb, prop.Attributes) || wasAdded;
                    sb.AppendLine("public {0}{1} {2} {{ get; set; }}".Fmt(@virtual, propType, prop.Name.SafeToken()));
                }
            }

            if (Config.AddResponseStatus
                && (type.Properties == null
                    || type.Properties.All(x => x.Name != "ResponseStatus")))
            {
                if (wasAdded) sb.AppendLine();
                wasAdded = true;

                AppendDataMember(sb, null, dataMemberIndex++);
                sb.AppendLine("public {0}ResponseStatus ResponseStatus {{ get; set; }}".Fmt(@virtual));
            }

            if (makeExtensible
                && (type.Properties == null
                    || type.Properties.All(x => x.Name != "ExtensionData")))
            {
                if (wasAdded) sb.AppendLine();
                wasAdded = true;

                sb.AppendLine("public {0}ExtensionDataObject ExtensionData {{ get; set; }}".Fmt(@virtual));
            }
        }
예제 #20
0
        private void AddTypeToSortedList(List<MetadataType> allTypes, List<MetadataType> sortedTypes, MetadataType metadataType)
        {
            if (sortedTypes.Contains(metadataType))
                return;

            if (metadataType == null)
                return;

            if (metadataType.Inherits == null)
            {
                sortedTypes.Add(metadataType);
                return;
            }

            var inheritedMetadataType = FindMetadataTypeByMetadataTypeName(allTypes, metadataType.Inherits);
            // Find and add base class first
            AddTypeToSortedList(allTypes,sortedTypes, inheritedMetadataType);

            if (!sortedTypes.Contains(metadataType))
                sortedTypes.Add(metadataType);
        }
예제 #21
0
        public MetadataCheckBox(MetadataType metadataType, string displayText, string count)
        {
            InitializeComponent();
            MetadataType = metadataType;
            cb.Enabled = PolicyBridge.AllowOverride(metadataType);
            cb.Checked = PolicyBridge.IsEnabled(metadataType);

            lblMetadataType.Enabled = PolicyBridge.AllowOverride(metadataType);
            lblCount.Enabled = PolicyBridge.AllowOverride(metadataType);

            if (!lblMetadataType.Enabled)
            {
                _toolTip = Utils.CreateToolTip(new List<Control>() {this, lblMetadataType, lblCount},
                                               Constants.YourAdminHasLockedThisSetting);
            }

            lblMetadataType.Text = displayText + ":";
            lblCount.Text = count;

            lblCount.Click += (sender, args) => Checked = !Checked;
            lblMetadataType.Click += (sender, args) => Checked = !Checked;
        }
        /// <summary>
        /// PersistentPutEventArgs Constructor
        /// </summary>
        /// <param name="parsed">a simple MessageParse</param>
        internal PersistentPutEventArgs(dynamic parsed)
        {
#if DEBUG
            FCP2Protocol.ArgsDebug(this, parsed);
#endif

            URI = parsed.URI;
            Verbosity = parsed.Verbosity;
            PriorityClass = parsed.PriorityClass;
            UploadFrom =parsed.UploadFrom;
            Filename = parsed.Filename;
            TargetFilename = parsed.TargetFilename;
            Metadata = new MetadataType(parsed.Metadata);
            ClientToken = parsed.ClientToken;
            Global = parsed.Global;
            DataLength = parsed.DataLength;
            MaxRetries = parsed.MaxRetries;

#if DEBUG
            parsed.PrintAccessCount();
#endif
        }
예제 #23
0
파일: Utils.cs 프로젝트: killbug2004/WSProf
        internal static ContentType ConvertContentType(MetadataType mdt)
        {
            switch (mdt)
            {
                case MetadataType.TrackedChange:
                    return ContentType.TrackChange;
                case MetadataType.Author:
                    return ContentType.Authors;
                case MetadataType.Link:
                    return ContentType.Links;
				case MetadataType.Properties:
					return ContentType.PDFProperties;
				case MetadataType.Attachments:
					return ContentType.PDFAttachments;
				case MetadataType.Bookmarks:
					return ContentType.PDFBookmarks;
				case MetadataType.Markups:
					return ContentType.PDFMarkups;
                default:
                    return (ContentType)Enum.Parse(typeof(ContentType), mdt.ToString());
            }
        }
예제 #24
0
 public GCStaticsNode(MetadataType type)
 {
     Debug.Assert(!type.IsCanonicalSubtype(CanonicalFormKind.Specific));
     _type = type;
     _preInitFieldInfos = PreInitFieldInfo.GetPreInitFieldInfos(_type);
 }
예제 #25
0
        private void AddTypeExtension(ref StringBuilderWrapper sbExt, MetadataType type, bool initCollections)
        {
            //Swift doesn't support extensions on same protocol used by Base and Sub types
            if (type.IsAbstract())
            {
                return;
            }

            var typeName = Type(type.Name, type.GenericArgs);

            typeName = typeName.LeftPart('<'); // Type<QueryResponse<T>> into correct mapping Type<QueryResponse>

            var typeNameOnly = typeName.LeftPart('<');

            sbExt.AppendLine();
            sbExt.AppendLine("extension {0} : JsonSerializable".Fmt(typeNameOnly));
            sbExt.AppendLine("{");
            sbExt = sbExt.Indent();

            sbExt.AppendLine("public static var typeName:String {{ return \"{0}\" }}".Fmt(typeName));

            //func typeConfig()

            var isGenericType = type.GenericArgs?.Length > 0 || type.Inherits?.GenericArgs?.Length > 0;

            if (!isGenericType)
            {
                sbExt.AppendLine("public static var metadata = Metadata.create([");
                sbExt = sbExt.Indent();
            }
            else
            {
                //Swift 2.0 doesn't allow stored static properties on generic types yet
                sbExt.AppendLine("public static var metadata:Metadata {");
                sbExt = sbExt.Indent();
                sbExt.AppendLine("return Metadata.create([");
            }

            sbExt = sbExt.Indent();

            foreach (var prop in GetPropertes(type))
            {
                var propType = FindType(prop.Type, prop.TypeNamespace, prop.GenericArgs);
                if (propType.IsInterface() ||
                    IgnorePropertyTypeNames.Contains(prop.Type) ||
                    IgnorePropertyNames.Contains(prop.Name))
                {
                    continue;
                }

                var fnName = "property";
                if (prop.IsArray() || ArrayTypes.Contains(prop.Type))
                {
                    fnName = initCollections
                        ? "arrayProperty"
                        : "optionalArrayProperty";
                }
                else if (DictionaryTypes.Contains(prop.Type))
                {
                    fnName = initCollections
                        ? "objectProperty"
                        : "optionalObjectProperty";
                }
                else
                {
                    if (propType != null && !propType.IsEnum.GetValueOrDefault())
                    {
                        fnName = "optionalObjectProperty";
                    }
                    else
                    {
                        fnName = "optionalProperty";
                    }
                }

                var propName      = prop.Name.SafeToken().PropertyStyle();
                var unescapedName = propName.UnescapeReserved();
                sbExt.AppendLine("Type<{0}>.{1}(\"{2}\", get: {{ $0.{3} }}, set: {{ $0.{3} = $1 }}),".Fmt(
                                     typeName, fnName, unescapedName, propName));
            }
            sbExt = sbExt.UnIndent();
            sbExt.AppendLine("])");
            sbExt = sbExt.UnIndent();

            if (isGenericType)
            {
                sbExt.AppendLine("}");
            }

            sbExt = sbExt.UnIndent();
            sbExt.AppendLine("}");
        }
예제 #26
0
 internal static extern IntPtr LibVLCMediaGetMeta(IntPtr media, MetadataType metadataType);
예제 #27
0
 public TypeNonGCStaticBaseGenericLookupResult(TypeDesc type)
 {
     Debug.Assert(type.IsRuntimeDeterminedSubtype, "Concrete static base in a generic dictionary?");
     Debug.Assert(type is MetadataType);
     _type = (MetadataType)type;
 }
 public ImportedThreadStaticsOffsetNode(MetadataType type, NodeFactory factory)
     : base("__imp_" + ThreadStaticsOffsetNode.GetMangledName(factory.NameMangler, type))
 {
 }
예제 #29
0
        public static MetadataType GetHelperType(this TypeSystemContext context, string name)
        {
            MetadataType helperType = context.SystemModule.GetKnownType("Internal.Runtime.CompilerHelpers", name);

            return(helperType);
        }
예제 #30
0
        public void AddProperties(StringBuilderWrapper sb, MetadataType type,
            bool includeResponseStatus,
            bool addPropertyAccessors,
            string settersReturnType)
        {
            var wasAdded = false;

            var sbInner = StringBuilderCacheAlt.Allocate();
            var sbAccessors = new StringBuilderWrapper(sbInner);
            if (addPropertyAccessors)
            {
                sbAccessors.AppendLine();
                sbAccessors = sbAccessors.Indent().Indent();
            }

            var dataMemberIndex = 1;
            if (type.Properties != null)
            {
                foreach (var prop in type.Properties)
                {
                    if (wasAdded) sb.AppendLine();

                    var propType = Type(prop.Type, prop.GenericArgs);

                    var fieldName = prop.Name.SafeToken().PropertyStyle();
                    var accessorName = fieldName.ToPascalCase();

                    wasAdded = AppendComments(sb, prop.Description);
                    wasAdded = AppendDataMember(sb, prop.DataMember, dataMemberIndex++) || wasAdded;
                    wasAdded = AppendAttributes(sb, prop.Attributes) || wasAdded;

                    if (!fieldName.IsKeyWord())
                    {
                        sb.AppendLine("public {0} {1} = null;".Fmt(propType, fieldName));
                    }
                    else
                    {
                        var originalName = fieldName;
                        fieldName = Char.ToUpper(fieldName[0]) + fieldName.SafeSubstring(1);
                        sb.AppendLine("@SerializedName(\"{0}\") public {1} {2} = null;".Fmt(originalName, propType, fieldName));
                    }

                    if (addPropertyAccessors)
                        sbAccessors.AppendPropertyAccessor(propType, fieldName, accessorName, settersReturnType);
                }
            }

            if (includeResponseStatus)
            {
                if (wasAdded) sb.AppendLine();

                AppendDataMember(sb, null, dataMemberIndex++);
                sb.AppendLine("public ResponseStatus {0} = null;".Fmt(typeof(ResponseStatus).Name.PropertyStyle()));

                if (addPropertyAccessors)
                    sbAccessors.AppendPropertyAccessor("ResponseStatus", "ResponseStatus", settersReturnType);
            }

            if (sbAccessors.Length > 0)
                sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbInner).TrimEnd()); //remove last \n
        }
예제 #31
0
 public bool CanGenerateMetadata(MetadataType type)
 {
     return((GetMetadataCategory(type) & MetadataCategory.Description) != 0);
 }
예제 #32
0
 internal Metadata(string path, MetadataType type, MetadataFormat format)
     : this(path, type, format, null, null)
 {
 }
예제 #33
0
        private void AddEnumExtension(ref StringBuilderWrapper sbExt, MetadataType type)
        {
            if (type.EnumNames == null)
            {
                return;
            }

            sbExt.AppendLine();
            var typeName = Type(type.Name, type.GenericArgs);

            sbExt.AppendLine("extension {0} : StringSerializable".Fmt(typeName));
            sbExt.AppendLine("{");
            sbExt = sbExt.Indent();

            sbExt.AppendLine("public static var typeName:String {{ return \"{0}\" }}".Fmt(typeName));

            //toJson()
            sbExt.AppendLine("public func toJson() -> String {");
            sbExt = sbExt.Indent();
            sbExt.AppendLine("return jsonStringRaw(toString())");
            sbExt = sbExt.UnIndent();
            sbExt.AppendLine("}");

            //toString()
            sbExt.AppendLine("public func toString() -> String {");
            sbExt = sbExt.Indent();
            sbExt.AppendLine("switch self {");
            foreach (var name in type.EnumNames)
            {
                sbExt.AppendLine("case .{0}: return \"{0}\"".Fmt(name));
            }
            sbExt.AppendLine("}");
            sbExt = sbExt.UnIndent();
            sbExt.AppendLine("}");

            //fromString()
            sbExt.AppendLine("public static func fromString(_ strValue:String) -> {0}? {{".Fmt(typeName));
            sbExt = sbExt.Indent();

            sbExt.AppendLine("switch strValue {");
            foreach (var name in type.EnumNames)
            {
                sbExt.AppendLine("case \"{0}\": return .{0}".Fmt(name));
            }
            sbExt.AppendLine("default: return nil");

            sbExt.AppendLine("}");
            sbExt = sbExt.UnIndent();
            sbExt.AppendLine("}");

            //fromObject()
            sbExt.AppendLine("public static func fromObject(_ any:Any) -> {0}? {{".Fmt(typeName));
            sbExt = sbExt.Indent();
            sbExt.AppendLine("switch any {");
            sbExt.AppendLine("case let i as Int: return {0}(rawValue: i)".Fmt(typeName));
            sbExt.AppendLine("case let s as String: return fromString(s)");
            sbExt.AppendLine("default: return nil");
            sbExt.AppendLine("}");
            sbExt = sbExt.UnIndent();
            sbExt.AppendLine("}");

            sbExt = sbExt.UnIndent();
            sbExt.AppendLine("}");
        }
예제 #34
0
        private void AddEnumExtension(ref StringBuilderWrapper sbExt, MetadataType type)
        {
            if (type.EnumNames == null) return;

            sbExt.AppendLine();
            var typeName = Type(type.Name, type.GenericArgs);
            sbExt.AppendLine("extension {0} : StringSerializable".Fmt(typeName));
            sbExt.AppendLine("{");
            sbExt = sbExt.Indent();

            sbExt.AppendLine("public static var typeName:String {{ return \"{0}\" }}".Fmt(typeName));

            //toJson()
            sbExt.AppendLine("public func toJson() -> String {");
            sbExt = sbExt.Indent();
            sbExt.AppendLine("return jsonStringRaw(toString())");
            sbExt = sbExt.UnIndent();
            sbExt.AppendLine("}");

            //toString()
            sbExt.AppendLine("public func toString() -> String {");
            sbExt = sbExt.Indent();
            sbExt.AppendLine("switch self {");
            foreach (var name in type.EnumNames)
            {
                sbExt.AppendLine("case .{0}: return \"{0}\"".Fmt(name));
            }
            sbExt.AppendLine("}");
            sbExt = sbExt.UnIndent();
            sbExt.AppendLine("}");

            //fromString()
            sbExt.AppendLine("public static func fromString(strValue:String) -> {0}? {{".Fmt(typeName));
            sbExt = sbExt.Indent();

            sbExt.AppendLine("switch strValue {");
            foreach (var name in type.EnumNames)
            {
                sbExt.AppendLine("case \"{0}\": return .{0}".Fmt(name));
            }
            sbExt.AppendLine("default: return nil");

            sbExt.AppendLine("}");
            sbExt = sbExt.UnIndent();
            sbExt.AppendLine("}");

            //fromObject()
            sbExt.AppendLine("public static func fromObject(any:AnyObject) -> {0}? {{".Fmt(typeName));
            sbExt = sbExt.Indent();
            sbExt.AppendLine("switch any {");
            sbExt.AppendLine("case let i as Int: return {0}(rawValue: i)".Fmt(typeName));
            sbExt.AppendLine("case let s as String: return fromString(s)");
            sbExt.AppendLine("default: return nil");
            sbExt.AppendLine("}");
            sbExt = sbExt.UnIndent();
            sbExt.AppendLine("}");

            sbExt = sbExt.UnIndent();
            sbExt.AppendLine("}");
        }
예제 #35
0
        private void ImportCall(ILOpcode opcode, int token)
        {
            // Strip runtime determined characteristics off of the method (because that's how RyuJIT operates)
            var        runtimeDeterminedMethod = (MethodDesc)_methodIL.GetObject(token);
            MethodDesc method = runtimeDeterminedMethod;

            if (runtimeDeterminedMethod.IsRuntimeDeterminedExactMethod)
            {
                method = runtimeDeterminedMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);
            }

            if (method.IsRawPInvoke())
            {
                // Raw P/invokes don't have any dependencies.
                return;
            }

            string reason = null;

            switch (opcode)
            {
            case ILOpcode.newobj:
                reason = "newobj"; break;

            case ILOpcode.call:
                reason = "call"; break;

            case ILOpcode.callvirt:
                reason = "callvirt"; break;

            case ILOpcode.ldftn:
                reason = "ldftn"; break;

            case ILOpcode.ldvirtftn:
                reason = "ldvirtftn"; break;

            default:
                Debug.Assert(false); break;
            }

            if (opcode == ILOpcode.newobj)
            {
                TypeDesc owningType = runtimeDeterminedMethod.OwningType;
                if (owningType.IsString)
                {
                    // String .ctor handled specially below
                }
                else if (owningType.IsGCPointer)
                {
                    if (owningType.IsRuntimeDeterminedSubtype)
                    {
                        _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.TypeHandle, owningType), reason);
                    }
                    else
                    {
                        _dependencies.Add(_factory.ConstructedTypeSymbol(owningType), reason);
                    }

                    if (owningType.IsMdArray)
                    {
                        _dependencies.Add(GetHelperEntrypoint(ReadyToRunHelper.NewMultiDimArr_NonVarArg), reason);
                        return;
                    }
                    else
                    {
                        _dependencies.Add(GetHelperEntrypoint(ReadyToRunHelper.NewObject), reason);
                    }
                }

                if (owningType.IsDelegate)
                {
                    // If this is a verifiable delegate construction sequence, the previous instruction is a ldftn/ldvirtftn
                    if (_previousInstructionOffset >= 0 && _ilBytes[_previousInstructionOffset] == (byte)ILOpcode.prefix1)
                    {
                        // TODO: for ldvirtftn we need to also check for the `dup` instruction, otherwise this is a normal newobj.

                        ILOpcode previousOpcode = (ILOpcode)(0x100 + _ilBytes[_previousInstructionOffset + 1]);
                        if (previousOpcode == ILOpcode.ldvirtftn || previousOpcode == ILOpcode.ldftn)
                        {
                            int                  delTargetToken    = ReadILTokenAt(_previousInstructionOffset + 2);
                            var                  delTargetMethod   = (MethodDesc)_methodIL.GetObject(delTargetToken);
                            TypeDesc             canonDelegateType = method.OwningType.ConvertToCanonForm(CanonicalFormKind.Specific);
                            DelegateCreationInfo info = _compilation.GetDelegateCtor(canonDelegateType, delTargetMethod, previousOpcode == ILOpcode.ldvirtftn);

                            if (info.NeedsRuntimeLookup)
                            {
                                _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.DelegateCtor, info), reason);
                            }
                            else
                            {
                                _dependencies.Add(_factory.ReadyToRunHelper(ReadyToRunHelperId.DelegateCtor, info), reason);
                            }

                            return;
                        }
                    }
                }
            }

            if (method.OwningType.IsDelegate && method.Name == "Invoke")
            {
                // TODO: might not want to do this if scanning for reflection.
                // This is expanded as an intrinsic, not a function call.
                return;
            }

            if (method.IsIntrinsic)
            {
                if (IsRuntimeHelpersInitializeArray(method))
                {
                    if (_previousInstructionOffset >= 0 && _ilBytes[_previousInstructionOffset] == (byte)ILOpcode.ldtoken)
                    {
                        return;
                    }
                }

                if (IsRuntimeTypeHandleGetValueInternal(method))
                {
                    if (_previousInstructionOffset >= 0 && _ilBytes[_previousInstructionOffset] == (byte)ILOpcode.ldtoken)
                    {
                        return;
                    }
                }

                if (IsActivatorDefaultConstructorOf(method))
                {
                    if (runtimeDeterminedMethod.IsRuntimeDeterminedExactMethod)
                    {
                        _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.DefaultConstructor, runtimeDeterminedMethod.Instantiation[0]), reason);
                    }
                    else
                    {
                        MethodDesc ctor = method.Instantiation[0].GetDefaultConstructor();
                        if (ctor == null)
                        {
                            MetadataType activatorType        = _compilation.TypeSystemContext.SystemModule.GetKnownType("System", "Activator");
                            MetadataType classWithMissingCtor = activatorType.GetKnownNestedType("ClassWithMissingConstructor");
                            ctor = classWithMissingCtor.GetParameterlessConstructor();
                        }
                        _dependencies.Add(_factory.CanonicalEntrypoint(ctor), reason);
                    }

                    return;
                }

                if (method.OwningType.IsByReferenceOfT && (method.IsConstructor || method.Name == "get_Value"))
                {
                    return;
                }

                if (IsEETypePtrOf(method))
                {
                    if (runtimeDeterminedMethod.IsRuntimeDeterminedExactMethod)
                    {
                        _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.TypeHandle, runtimeDeterminedMethod.Instantiation[0]), reason);
                    }
                    else
                    {
                        _dependencies.Add(_factory.ConstructedTypeSymbol(method.Instantiation[0]), reason);
                    }
                    return;
                }
            }

            TypeDesc exactType = method.OwningType;

            if (method.IsNativeCallable && (opcode != ILOpcode.ldftn && opcode != ILOpcode.ldvirtftn))
            {
                ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramNativeCallable, method);
            }

            bool resolvedConstraint    = false;
            bool forceUseRuntimeLookup = false;

            MethodDesc methodAfterConstraintResolution = method;

            if (_constrained != null)
            {
                // We have a "constrained." call.  Try a partial resolve of the constraint call.  Note that this
                // will not necessarily resolve the call exactly, since we might be compiling
                // shared generic code - it may just resolve it to a candidate suitable for
                // JIT compilation, and require a runtime lookup for the actual code pointer
                // to call.

                TypeDesc constrained = _constrained;
                if (constrained.IsRuntimeDeterminedSubtype)
                {
                    constrained = constrained.ConvertToCanonForm(CanonicalFormKind.Specific);
                }

                MethodDesc directMethod = constrained.GetClosestDefType().TryResolveConstraintMethodApprox(method.OwningType, method, out forceUseRuntimeLookup);
                if (directMethod == null && constrained.IsEnum)
                {
                    // Constrained calls to methods on enum methods resolve to System.Enum's methods. System.Enum is a reference
                    // type though, so we would fail to resolve and box. We have a special path for those to avoid boxing.
                    directMethod = _compilation.TypeSystemContext.TryResolveConstrainedEnumMethod(constrained, method);
                }

                if (directMethod != null)
                {
                    // Either
                    //    1. no constraint resolution at compile time (!directMethod)
                    // OR 2. no code sharing lookup in call
                    // OR 3. we have have resolved to an instantiating stub

                    methodAfterConstraintResolution = directMethod;

                    Debug.Assert(!methodAfterConstraintResolution.OwningType.IsInterface);
                    resolvedConstraint = true;

                    exactType = constrained;
                }
                else if (constrained.IsValueType)
                {
                    // We'll need to box `this`. Note we use _constrained here, because the other one is canonical.
                    AddBoxingDependencies(_constrained, reason);
                }
            }

            MethodDesc targetMethod = methodAfterConstraintResolution;

            bool exactContextNeedsRuntimeLookup;

            if (targetMethod.HasInstantiation)
            {
                exactContextNeedsRuntimeLookup = targetMethod.IsSharedByGenericInstantiations;
            }
            else
            {
                exactContextNeedsRuntimeLookup = exactType.IsCanonicalSubtype(CanonicalFormKind.Any);
            }

            //
            // Determine whether to perform direct call
            //

            bool directCall = false;

            if (targetMethod.Signature.IsStatic)
            {
                // Static methods are always direct calls
                directCall = true;
            }
            else if (targetMethod.OwningType.IsInterface)
            {
                // Force all interface calls to be interpreted as if they are virtual.
                directCall = false;
            }
            else if ((opcode != ILOpcode.callvirt && opcode != ILOpcode.ldvirtftn) || resolvedConstraint)
            {
                directCall = true;
            }
            else
            {
                if (!targetMethod.IsVirtual || targetMethod.IsFinal || targetMethod.OwningType.IsSealed())
                {
                    directCall = true;
                }
            }

            bool allowInstParam = opcode != ILOpcode.ldvirtftn && opcode != ILOpcode.ldftn;

            if (directCall && !allowInstParam && targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific).RequiresInstArg())
            {
                // Needs a single address to call this method but the method needs a hidden argument.
                // We need a fat function pointer for this that captures both things.

                if (exactContextNeedsRuntimeLookup)
                {
                    _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.MethodEntry, runtimeDeterminedMethod), reason);
                }
                else
                {
                    _dependencies.Add(_factory.FatFunctionPointer(runtimeDeterminedMethod), reason);
                }
            }
            else if (directCall)
            {
                bool referencingArrayAddressMethod = false;

                if (targetMethod.IsIntrinsic)
                {
                    // If this is an intrinsic method with a callsite-specific expansion, this will replace
                    // the method with a method the intrinsic expands into. If it's not the special intrinsic,
                    // method stays unchanged.
                    targetMethod = _compilation.ExpandIntrinsicForCallsite(targetMethod, _canonMethod);

                    // Array address method requires special dependency tracking.
                    referencingArrayAddressMethod = targetMethod.IsArrayAddressMethod();
                }

                MethodDesc concreteMethod = targetMethod;
                targetMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);

                if (targetMethod.IsConstructor && targetMethod.OwningType.IsString)
                {
                    _dependencies.Add(_factory.StringAllocator(targetMethod), reason);
                }
                else if (exactContextNeedsRuntimeLookup)
                {
                    if (targetMethod.IsSharedByGenericInstantiations && !resolvedConstraint && !referencingArrayAddressMethod)
                    {
                        ISymbolNode instParam = null;

                        if (targetMethod.RequiresInstMethodDescArg())
                        {
                            instParam = GetGenericLookupHelper(ReadyToRunHelperId.MethodDictionary, runtimeDeterminedMethod);
                        }
                        else if (targetMethod.RequiresInstMethodTableArg())
                        {
                            bool hasHiddenParameter = true;

                            if (targetMethod.IsIntrinsic)
                            {
                                if (_factory.TypeSystemContext.IsSpecialUnboxingThunkTargetMethod(targetMethod))
                                {
                                    hasHiddenParameter = false;
                                }
                            }

                            if (hasHiddenParameter)
                            {
                                instParam = GetGenericLookupHelper(ReadyToRunHelperId.TypeHandle, runtimeDeterminedMethod.OwningType);
                            }
                        }

                        if (instParam != null)
                        {
                            _dependencies.Add(instParam, reason);
                        }

                        _dependencies.Add(_factory.RuntimeDeterminedMethod(runtimeDeterminedMethod), reason);
                    }
                    else
                    {
                        Debug.Assert(!forceUseRuntimeLookup);
                        _dependencies.Add(_factory.MethodEntrypoint(targetMethod), reason);

                        if (targetMethod.RequiresInstMethodTableArg() && resolvedConstraint)
                        {
                            if (_constrained.IsRuntimeDeterminedSubtype)
                            {
                                _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.TypeHandle, _constrained), reason);
                            }
                            else
                            {
                                _dependencies.Add(_factory.ConstructedTypeSymbol(_constrained), reason);
                            }
                        }

                        if (referencingArrayAddressMethod && !_isReadOnly)
                        {
                            // Address method is special - it expects an instantiation argument, unless a readonly prefix was applied.
                            _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.TypeHandle, runtimeDeterminedMethod.OwningType), reason);
                        }
                    }
                }
                else
                {
                    ISymbolNode instParam = null;

                    if (targetMethod.RequiresInstMethodDescArg())
                    {
                        instParam = _compilation.NodeFactory.MethodGenericDictionary(concreteMethod);
                    }
                    else if (targetMethod.RequiresInstMethodTableArg() || (referencingArrayAddressMethod && !_isReadOnly))
                    {
                        // Ask for a constructed type symbol because we need the vtable to get to the dictionary
                        instParam = _compilation.NodeFactory.ConstructedTypeSymbol(concreteMethod.OwningType);
                    }

                    if (instParam != null)
                    {
                        _dependencies.Add(instParam, reason);

                        if (!referencingArrayAddressMethod)
                        {
                            _dependencies.Add(_compilation.NodeFactory.ShadowConcreteMethod(concreteMethod), reason);
                        }
                        else
                        {
                            // We don't want array Address method to be modeled in the generic dependency analysis.
                            // The method doesn't actually have runtime determined dependencies (won't do
                            // any generic lookups).
                            _dependencies.Add(_compilation.NodeFactory.MethodEntrypoint(targetMethod), reason);
                        }
                    }
                    else if (targetMethod.AcquiresInstMethodTableFromThis())
                    {
                        _dependencies.Add(_compilation.NodeFactory.ShadowConcreteMethod(concreteMethod), reason);
                    }
                    else
                    {
                        _dependencies.Add(_compilation.NodeFactory.MethodEntrypoint(targetMethod), reason);
                    }
                }
            }
            else if (method.HasInstantiation)
            {
                // Generic virtual method call

                if (exactContextNeedsRuntimeLookup)
                {
                    _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.MethodHandle, runtimeDeterminedMethod), reason);
                }
                else
                {
                    _dependencies.Add(_factory.RuntimeMethodHandle(runtimeDeterminedMethod), reason);
                }

                _dependencies.Add(GetHelperEntrypoint(ReadyToRunHelper.GVMLookupForSlot), reason);
            }
            else if (method.OwningType.IsInterface)
            {
                if (exactContextNeedsRuntimeLookup)
                {
                    _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.VirtualDispatchCell, runtimeDeterminedMethod), reason);
                }
                else
                {
                    _dependencies.Add(_factory.InterfaceDispatchCell(method), reason);
                }
            }
            else if (_compilation.HasFixedSlotVTable(method.OwningType))
            {
                // No dependencies: virtual call through the vtable
            }
            else
            {
                MethodDesc slotDefiningMethod = targetMethod.IsNewSlot ?
                                                targetMethod : MetadataVirtualMethodAlgorithm.FindSlotDefiningMethodForVirtualMethod(targetMethod);
                _dependencies.Add(_factory.VirtualMethodUse(slotDefiningMethod), reason);
            }
        }
예제 #36
0
 public static bool IsNestedPublic(this MetadataType mdType)
 {
     return(mdType.GetTypeDefinition() is EcmaType ecmaType &&
            (ecmaType.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic);
 }
예제 #37
0
        private string AppendType(ref StringBuilderWrapper sb, ref StringBuilderWrapper sbExt, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            //sb = sb.Indent();

            var hasGenericBaseType = type.Inherits != null && !type.Inherits.GenericArgs.IsEmpty();

            if (Config.ExcludeGenericBaseTypes && hasGenericBaseType)
            {
                sb.AppendLine("//Excluded {0} : {1}<{2}>".Fmt(type.Name, type.Inherits.Name.LeftPart('`'), string.Join(",", type.Inherits.GenericArgs)));
                return(lastNS);
            }

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("public enum {0} : Int".Fmt(Type(type.Name, type.GenericArgs)));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null
                            ? "case {0}".Fmt(name)
                            : "case {0} = {1}".Fmt(name, value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");

                AddEnumExtension(ref sbExt, type);
            }
            else
            {
                var defType  = "class";
                var typeName = Type(type.Name, type.GenericArgs).AddGenericConstraints();
                var extends  = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    var baseType = Type(type.Inherits).InheritedType();

                    //Swift requires re-declaring base type generics definition on super type
                    var genericDefPos = baseType.IndexOf("<");
                    if (genericDefPos >= 0)
                    {
                        //Need to declare BaseType is JsonSerializable
                        var subBaseType = baseType.Substring(genericDefPos)
                                          .AddGenericConstraints();

                        typeName += subBaseType;
                    }

                    extends.Add(baseType);
                }
                else if (Config.BaseClass != null && !type.IsInterface())
                {
                    extends.Add(Config.BaseClass);
                }

                var typeAliases = new List <string>();

                if (options.ImplementsFn != null)
                {
                    //Swift doesn't support Generic Interfaces like IReturn<T>
                    //Converting them into protocols with typealiases instead
                    ExtractTypeAliases(options, typeAliases, extends, ref sbExt);

                    if (!type.Implements.IsEmpty())
                    {
                        type.Implements.Each(x => extends.Add(Type(x)));
                    }
                }

                if (type.IsInterface())
                {
                    defType = "protocol";

                    //Extract Protocol Arguments into different typealiases
                    if (!type.GenericArgs.IsEmpty())
                    {
                        typeName = Type(type.Name, null);
                        foreach (var arg in type.GenericArgs)
                        {
                            typeAliases.Add($"associatedtype {arg}");
                        }
                    }
                }

                var extend = extends.Count > 0
                    ? " : " + (string.Join(", ", extends.ToArray()))
                    : "";

                sb.AppendLine($"public {defType} {typeName}{extend}");
                sb.AppendLine("{");

                sb = sb.Indent();

                if (typeAliases.Count > 0)
                {
                    foreach (var typeAlias in typeAliases)
                    {
                        sb.AppendLine(typeAlias);
                    }
                    sb.AppendLine();
                }

                if (!type.IsInterface())
                {
                    if (extends.Count > 0 && OverrideInitForBaseClasses.Contains(extends[0]))
                    {
                        sb.AppendLine("required public override init(){}");
                    }
                    else
                    {
                        sb.AppendLine("required public init(){}");
                    }
                }

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine($"public var {"Version".PropertyStyle()}:Int = {Config.AddImplicitVersion}");
                }

                var initCollections = feature.ShouldInitializeCollections(type, Config.InitializeCollections);
                AddProperties(sb, type,
                              initCollections: !type.IsInterface() && initCollections,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                sb = sb.UnIndent();
                sb.AppendLine("}");

                if (!type.IsInterface())
                {
                    AddTypeExtension(ref sbExt, type,
                                     initCollections: Config.InitializeCollections);
                }
            }

            //sb = sb.UnIndent();

            return(lastNS);
        }
예제 #38
0
 internal static extern bool StreamDecoderSetMetadataRespond(
     StreamDecoderHandle handle,
     MetadataType metadataType);
예제 #39
0
        /// <summary>
        /// Provides method bodies for intrinsics recognized by the compiler.
        /// It can return null if it's not an intrinsic recognized by the compiler,
        /// but an intrinsic e.g. recognized by codegen.
        /// </summary>
        private MethodIL TryGetIntrinsicMethodIL(MethodDesc method)
        {
            Debug.Assert(method.IsIntrinsic);

            MetadataType owningType = method.OwningType as MetadataType;

            if (owningType == null)
            {
                return(null);
            }

            switch (owningType.Name)
            {
            case "Interlocked":
            {
                if (owningType.Namespace == "System.Threading")
                {
                    return(InterlockedIntrinsics.EmitIL(method));
                }
            }
            break;

            case "Unsafe":
            {
                if (owningType.Namespace == "Internal.Runtime.CompilerServices")
                {
                    return(UnsafeIntrinsics.EmitIL(method));
                }
            }
            break;

            case "Volatile":
            {
                if (owningType.Namespace == "System.Threading")
                {
                    return(VolatileIntrinsics.EmitIL(method));
                }
            }
            break;

            case "Debug":
            {
                if (owningType.Namespace == "System.Diagnostics" && method.Name == "DebugBreak")
                {
                    return(new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.break_, (byte)ILOpcode.ret }, Array.Empty <LocalVariableDefinition>(), null));
                }
            }
            break;

            case "EETypePtr":
            {
                if (owningType.Namespace == "System" && method.Name == "EETypePtrOf")
                {
                    return(EETypePtrOfIntrinsic.EmitIL(method));
                }
            }
            break;

            case "RuntimeAugments":
            {
                if (owningType.Namespace == "Internal.Runtime.Augments" && method.Name == "GetCanonType")
                {
                    return(GetCanonTypeIntrinsic.EmitIL(method));
                }
            }
            break;

            case "EEType":
            {
                if (owningType.Namespace == "Internal.Runtime" && method.Name == "get_SupportsRelativePointers")
                {
                    ILOpcode value = method.Context.Target.SupportsRelativePointers ?
                                     ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0;
                    return(new ILStubMethodIL(method, new byte[] { (byte)value, (byte)ILOpcode.ret }, Array.Empty <LocalVariableDefinition>(), null));
                }
            }
            break;
            }

            return(null);
        }
예제 #40
0
        /// <summary>
        /// Provides method bodies for intrinsics recognized by the compiler that
        /// are specialized per instantiation. It can return null if the intrinsic
        /// is not recognized.
        /// </summary>
        private MethodIL TryGetPerInstantiationIntrinsicMethodIL(MethodDesc method)
        {
            Debug.Assert(method.IsIntrinsic);

            MetadataType owningType = method.OwningType.GetTypeDefinition() as MetadataType;

            if (owningType == null)
            {
                return(null);
            }

            string methodName = method.Name;

            switch (owningType.Name)
            {
            case "RuntimeHelpers":
            {
                if (owningType.Namespace == "System.Runtime.CompilerServices")
                {
                    return(RuntimeHelpersIntrinsics.EmitIL(method));
                }
            }
            break;

            case "Comparer`1":
            {
                if (methodName == "Create" && owningType.Namespace == "System.Collections.Generic")
                {
                    return(ComparerIntrinsics.EmitComparerCreate(method));
                }
            }
            break;

            case "EqualityComparer`1":
            {
                if (methodName == "Create" && owningType.Namespace == "System.Collections.Generic")
                {
                    return(ComparerIntrinsics.EmitEqualityComparerCreate(method));
                }
            }
            break;

            case "EqualityComparerHelpers":
            {
                if (owningType.Namespace != "Internal.IntrinsicSupport")
                {
                    return(null);
                }

                if (methodName == "EnumOnlyEquals")
                {
                    // EnumOnlyEquals would basically like to do this:
                    // static bool EnumOnlyEquals<T>(T x, T y) where T: struct => x == y;
                    // This is not legal though.
                    // We don't want to do this:
                    // static bool EnumOnlyEquals<T>(T x, T y) where T: struct => x.Equals(y);
                    // Because it would box y.
                    // So we resort to some per-instantiation magic.

                    TypeDesc elementType = method.Instantiation[0];
                    if (!elementType.IsEnum)
                    {
                        return(null);
                    }

                    ILOpcode convInstruction;
                    if (((DefType)elementType).InstanceFieldSize.AsInt <= 4)
                    {
                        convInstruction = ILOpcode.conv_i4;
                    }
                    else
                    {
                        Debug.Assert(((DefType)elementType).InstanceFieldSize.AsInt == 8);
                        convInstruction = ILOpcode.conv_i8;
                    }

                    return(new ILStubMethodIL(method, new byte[] {
                            (byte)ILOpcode.ldarg_0,
                            (byte)convInstruction,
                            (byte)ILOpcode.ldarg_1,
                            (byte)convInstruction,
                            (byte)ILOpcode.prefix1, unchecked ((byte)ILOpcode.ceq),
                            (byte)ILOpcode.ret,
                        },
                                              Array.Empty <LocalVariableDefinition>(), null));
                }
                else if (methodName == "GetComparerForReferenceTypesOnly")
                {
                    TypeDesc elementType = method.Instantiation[0];
                    if (!elementType.IsRuntimeDeterminedSubtype &&
                        !elementType.IsCanonicalSubtype(CanonicalFormKind.Any) &&
                        !elementType.IsGCPointer)
                    {
                        return(new ILStubMethodIL(method, new byte[] {
                                (byte)ILOpcode.ldnull,
                                (byte)ILOpcode.ret
                            },
                                                  Array.Empty <LocalVariableDefinition>(), null));
                    }
                }
                else if (methodName == "StructOnlyEquals")
                {
                    TypeDesc elementType = method.Instantiation[0];
                    if (!elementType.IsRuntimeDeterminedSubtype &&
                        !elementType.IsCanonicalSubtype(CanonicalFormKind.Any) &&
                        !elementType.IsGCPointer)
                    {
                        Debug.Assert(elementType.IsValueType);

                        TypeSystemContext context    = elementType.Context;
                        MetadataType      helperType = context.SystemModule.GetKnownType("Internal.IntrinsicSupport", "EqualityComparerHelpers");

                        MethodDesc methodToCall;
                        if (elementType.IsEnum)
                        {
                            methodToCall = helperType.GetKnownMethod("EnumOnlyEquals", null).MakeInstantiatedMethod(elementType);
                        }
                        else if (elementType.IsNullable && ComparerIntrinsics.ImplementsIEquatable(elementType.Instantiation[0]))
                        {
                            methodToCall = helperType.GetKnownMethod("StructOnlyEqualsNullable", null).MakeInstantiatedMethod(elementType.Instantiation[0]);
                        }
                        else if (ComparerIntrinsics.ImplementsIEquatable(elementType))
                        {
                            methodToCall = helperType.GetKnownMethod("StructOnlyEqualsIEquatable", null).MakeInstantiatedMethod(elementType);
                        }
                        else
                        {
                            methodToCall = helperType.GetKnownMethod("StructOnlyNormalEquals", null).MakeInstantiatedMethod(elementType);
                        }

                        return(new ILStubMethodIL(method, new byte[]
                            {
                                (byte)ILOpcode.ldarg_0,
                                (byte)ILOpcode.ldarg_1,
                                (byte)ILOpcode.call, 1, 0, 0, 0,
                                (byte)ILOpcode.ret
                            },
                                                  Array.Empty <LocalVariableDefinition>(), new object[] { methodToCall }));
                    }
                }
            }
            break;
            }

            return(null);
        }
예제 #41
0
        public MethodIL EmitIL()
        {
            MethodSignature targetMethodSignature = _targetMethod.Signature;

            // We have 4 code streams:
            // - _marshallingCodeStream is used to convert each argument into a native type and
            // store that into the local
            // - callsiteSetupCodeStream is used to used to load each previously generated local
            // and call the actual target native method.
            // - _returnValueMarshallingCodeStream is used to convert the native return value
            // to managed one.
            // - _unmarshallingCodestream is used to propagate [out] native arguments values to
            // managed ones.
            _emitter = new ILEmitter();
            ILCodeStream fnptrLoadStream = _emitter.NewCodeStream();

            _marshallingCodeStream = _emitter.NewCodeStream();
            ILCodeStream callsiteSetupCodeStream = _emitter.NewCodeStream();

            _returnValueMarshallingCodeStream = _emitter.NewCodeStream();
            _unmarshallingCodestream          = _emitter.NewCodeStream();

            TypeDesc[] nativeParameterTypes = new TypeDesc[targetMethodSignature.Length];

            //
            // Parameter marshalling
            //

            //
            // Convert each argument to something we can pass to native and store it in a local.
            // Then load the local in the second code stream.
            //
            for (int i = 0; i < targetMethodSignature.Length; i++)
            {
                // TODO: throw if there's custom marshalling

                _marshallingCodeStream.EmitLdArg(i);

                TypeDesc nativeType = MarshalArgument(targetMethodSignature[i]);

                nativeParameterTypes[i] = nativeType;

                ILLocalVariable vMarshalledTypeTemp = _emitter.NewLocal(nativeType);
                _marshallingCodeStream.EmitStLoc(vMarshalledTypeTemp);

                callsiteSetupCodeStream.EmitLdLoc(vMarshalledTypeTemp);
            }

            //
            // Return value marshalling
            //

            // TODO: throw if SetLastError is true
            // TODO: throw if there's custom marshalling

            TypeDesc nativeReturnType = MarshalReturnValue(targetMethodSignature.ReturnType);

            if (UseLazyResolution(_targetMethod, _importMetadata.Module))
            {
                MetadataType lazyHelperType   = _targetMethod.Context.GetHelperType("InteropHelpers");
                FieldDesc    lazyDispatchCell = new PInvokeLazyFixupField((DefType)_targetMethod.OwningType, _importMetadata);
                fnptrLoadStream.Emit(ILOpcode.ldsflda, _emitter.NewToken(lazyDispatchCell));
                fnptrLoadStream.Emit(ILOpcode.call, _emitter.NewToken(lazyHelperType.GetKnownMethod("ResolvePInvoke", null)));

                MethodSignatureFlags unmanagedCallConv = PInvokeMetadata.GetUnmanagedCallingConvention(_importMetadata.Attributes);

                MethodSignature nativeCalliSig = new MethodSignature(
                    targetMethodSignature.Flags | unmanagedCallConv, 0, nativeReturnType, nativeParameterTypes);

                ILLocalVariable vNativeFunctionPointer = _emitter.NewLocal(_targetMethod.Context.GetWellKnownType(WellKnownType.IntPtr));
                fnptrLoadStream.EmitStLoc(vNativeFunctionPointer);
                callsiteSetupCodeStream.EmitLdLoc(vNativeFunctionPointer);
                callsiteSetupCodeStream.Emit(ILOpcode.calli, _emitter.NewToken(nativeCalliSig));
            }
            else
            {
                // Eager call
                PInvokeMetadata nativeImportMetadata =
                    new PInvokeMetadata(_importMetadata.Module, _importMetadata.Name ?? _targetMethod.Name, _importMetadata.Attributes);

                MethodSignature nativeSig = new MethodSignature(
                    targetMethodSignature.Flags, 0, nativeReturnType, nativeParameterTypes);

                MethodDesc nativeMethod =
                    new PInvokeTargetNativeMethod(_targetMethod.OwningType, nativeSig, nativeImportMetadata);

                callsiteSetupCodeStream.Emit(ILOpcode.call, _emitter.NewToken(nativeMethod));
            }

            _unmarshallingCodestream.Emit(ILOpcode.ret);

            return(_emitter.Link(_targetMethod));
        }
예제 #42
0
 internal static extern void LibVLCMediaSetMeta(IntPtr media, MetadataType metadataType, [MarshalAs(UnmanagedType.LPStr)] string value);
예제 #43
0
 internal static extern MetadataBlockHandle MetadataObjectNew(
     MetadataType blockType);
예제 #44
0
 public bool GeneratesMetadata(MetadataType typeDef)
 {
     return(_typeGeneratesMetadata(typeDef));
 }
예제 #45
0
        public string GetCode(MetadataTypes metadata, IRequest request, INativeTypesMetadata nativeTypes)
        {
            var typeNamespaces = new HashSet <string>();

            RemoveIgnoredTypes(metadata);
            metadata.Types.Each(x => typeNamespaces.Add(x.Namespace));
            metadata.Operations.Each(x => typeNamespaces.Add(x.Request.Namespace));

            var defaultImports = new List <string>(DefaultImports);

            if (!Config.DefaultImports.IsEmpty())
            {
                defaultImports = Config.DefaultImports;
            }
            else if (ReferencesGson(metadata))
            {
                if (!defaultImports.Contains(GSonAnnotationsNamespace))
                {
                    defaultImports.Add(GSonAnnotationsNamespace);
                }
                if (!defaultImports.Contains(GSonReflectNamespace))
                {
                    defaultImports.Add(GSonReflectNamespace);
                }
            }

            var defaultNamespace = Config.GlobalNamespace ?? DefaultGlobalNamespace;

            Func <string, string> defaultValue = k =>
                                                 request.QueryString[k].IsNullOrEmpty() ? "//" : "";

            var sbInner = StringBuilderCache.Allocate();
            var sb      = new StringBuilderWrapper(sbInner);

            sb.AppendLine("/* Options:");
            sb.AppendLine("Date: {0}".Fmt(DateTime.Now.ToString("s").Replace("T", " ")));
            sb.AppendLine("Version: {0}".Fmt(Env.ServiceStackVersion));
            sb.AppendLine("Tip: {0}".Fmt(HelpMessages.NativeTypesDtoOptionsTip.Fmt("//")));
            sb.AppendLine("BaseUrl: {0}".Fmt(Config.BaseUrl));
            sb.AppendLine();
            sb.AppendLine("{0}Package: {1}".Fmt(defaultValue("Package"), Config.Package));
            sb.AppendLine("{0}GlobalNamespace: {1}".Fmt(defaultValue("GlobalNamespace"), defaultNamespace));
            sb.AppendLine("{0}AddPropertyAccessors: {1}".Fmt(defaultValue("AddPropertyAccessors"), Config.AddPropertyAccessors));
            sb.AppendLine("{0}SettersReturnThis: {1}".Fmt(defaultValue("SettersReturnThis"), Config.SettersReturnThis));
            sb.AppendLine("{0}AddServiceStackTypes: {1}".Fmt(defaultValue("AddServiceStackTypes"), Config.AddServiceStackTypes));
            sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(defaultValue("AddResponseStatus"), Config.AddResponseStatus));
            sb.AppendLine("{0}AddDescriptionAsComments: {1}".Fmt(defaultValue("AddDescriptionAsComments"), Config.AddDescriptionAsComments));
            sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(defaultValue("AddImplicitVersion"), Config.AddImplicitVersion));
            sb.AppendLine("{0}IncludeTypes: {1}".Fmt(defaultValue("IncludeTypes"), Config.IncludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}ExcludeTypes: {1}".Fmt(defaultValue("ExcludeTypes"), Config.ExcludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}TreatTypesAsStrings: {1}".Fmt(defaultValue("TreatTypesAsStrings"), Config.TreatTypesAsStrings.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}DefaultImports: {1}".Fmt(defaultValue("DefaultImports"), defaultImports.Join(",")));

            sb.AppendLine("*/");
            sb.AppendLine();

            foreach (var typeName in Config.TreatTypesAsStrings.Safe())
            {
                TypeAliases[typeName] = "String";
            }

            if (Config.Package != null)
            {
                sb.AppendLine("package {0};".Fmt(Config.Package));
                sb.AppendLine();
            }

            string lastNS = null;

            var existingTypes = new HashSet <string>();

            var requestTypes    = metadata.Operations.Select(x => x.Request).ToHashSet();
            var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request);
            var responseTypes   = metadata.Operations
                                  .Where(x => x.Response != null)
                                  .Select(x => x.Response).ToHashSet();
            var types = metadata.Types.ToHashSet();

            AllTypes.AddRange(requestTypes);
            AllTypes.AddRange(responseTypes);
            AllTypes.AddRange(types);

            AllTypes = FilterTypes(AllTypes);

            //TypeScript doesn't support reusing same type name with different generic airity
            var conflictPartialNames = AllTypes.Map(x => x.Name).Distinct()
                                       .GroupBy(g => g.LeftPart('`'))
                                       .Where(g => g.Count() > 1)
                                       .Select(g => g.Key)
                                       .ToList();

            this.conflictTypeNames = AllTypes
                                     .Where(x => conflictPartialNames.Any(name => x.Name.StartsWith(name)))
                                     .Map(x => x.Name);

            defaultImports.Each(x => sb.AppendLine("import {0};".Fmt(x)));
            sb.AppendLine();

            sb.AppendLine("public class {0}".Fmt(defaultNamespace.SafeToken()));
            sb.AppendLine("{");

            //ServiceStack core interfaces
            foreach (var type in AllTypes)
            {
                var fullTypeName = type.GetFullName();
                if (requestTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName))
                    {
                        MetadataType          response = null;
                        MetadataOperationType operation;
                        if (requestTypesMap.TryGetValue(type, out operation))
                        {
                            response = operation.Response;
                        }

                        lastNS = AppendType(ref sb, type, lastNS,
                                            new CreateTypeOptions
                        {
                            ImplementsFn = () =>
                            {
                                if (!Config.AddReturnMarker &&
                                    !type.ReturnVoidMarker &&
                                    type.ReturnMarkerTypeName == null)
                                {
                                    return(null);
                                }

                                if (type.ReturnVoidMarker)
                                {
                                    return("IReturnVoid");
                                }
                                if (type.ReturnMarkerTypeName != null)
                                {
                                    return(Type("IReturn`1", new[] { Type(type.ReturnMarkerTypeName) }));
                                }
                                return(response != null
                                        ? Type("IReturn`1", new[] { Type(response.Name, response.GenericArgs) })
                                        : null);
                            },
                            IsRequest = true,
                        });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (responseTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName) &&
                        !Config.IgnoreTypesInNamespaces.Contains(type.Namespace))
                    {
                        lastNS = AppendType(ref sb, type, lastNS,
                                            new CreateTypeOptions
                        {
                            IsResponse = true,
                        });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (types.Contains(type) && !existingTypes.Contains(fullTypeName))
                {
                    lastNS = AppendType(ref sb, type, lastNS,
                                        new CreateTypeOptions {
                        IsType = true
                    });

                    existingTypes.Add(fullTypeName);
                }
            }

            sb.AppendLine();
            sb.AppendLine("}");

            return(StringBuilderCache.ReturnAndFree(sbInner));
        }
예제 #46
0
        /// <summary>
        /// Generates IL for the IsSupported property that reads this information from a field initialized by the runtime
        /// at startup. Returns null for hardware intrinsics whose support level is known at compile time
        /// (i.e. they're known to be always supported or always unsupported).
        /// </summary>
        public static MethodIL EmitIsSupportedIL(MethodDesc method, FieldDesc isSupportedField)
        {
            Debug.Assert(IsIsSupportedMethod(method));
            Debug.Assert(isSupportedField.IsStatic && isSupportedField.FieldType.IsWellKnownType(WellKnownType.Int32));

            TargetDetails target     = method.Context.Target;
            MetadataType  owningType = (MetadataType)method.OwningType;

            // Check for case of nested "X64" types
            if (owningType.Name == "X64")
            {
                if (target.Architecture != TargetArchitecture.X64)
                {
                    return(null);
                }

                // Un-nest the type so that we can do a name match
                owningType = (MetadataType)owningType.ContainingType;
            }

            int flag;

            if ((target.Architecture == TargetArchitecture.X64 || target.Architecture == TargetArchitecture.X86) &&
                owningType.Namespace == "System.Runtime.Intrinsics.X86")
            {
                switch (owningType.Name)
                {
                case "Aes":
                    flag = XArchIntrinsicConstants.Aes;
                    break;

                case "Pclmulqdq":
                    flag = XArchIntrinsicConstants.Pclmulqdq;
                    break;

                case "Sse3":
                    flag = XArchIntrinsicConstants.Sse3;
                    break;

                case "Ssse3":
                    flag = XArchIntrinsicConstants.Ssse3;
                    break;

                case "Lzcnt":
                    flag = XArchIntrinsicConstants.Lzcnt;
                    break;

                // NOTE: this switch is complemented by IsKnownSupportedIntrinsicAtCompileTime
                // in the method below.
                default:
                    return(null);
                }
            }
            else
            {
                return(null);
            }

            var          emit       = new ILEmitter();
            ILCodeStream codeStream = emit.NewCodeStream();

            codeStream.Emit(ILOpcode.ldsfld, emit.NewToken(isSupportedField));
            codeStream.EmitLdc(flag);
            codeStream.Emit(ILOpcode.and);
            codeStream.EmitLdc(0);
            codeStream.Emit(ILOpcode.cgt_un);
            codeStream.Emit(ILOpcode.ret);

            return(emit.Link(method));
        }
예제 #47
0
 public ArrayIndexExpression(Expression array, Expression index, MetadataType type, TypeReference objectType)
     : this(array, index, type, objectType, instruction : null)
 {
 }
예제 #48
0
 public InlineArrayCandidate(MetadataType type, uint length)
 {
     ElementType = type;
     Length      = length;
 }
예제 #49
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            var typeName = Type(type.Name, type.GenericArgs);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("public static enum {0}".Fmt(typeName));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    var hasIntValue = false;
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;

                        var delim       = i == type.EnumNames.Count - 1 ? ";" : ",";
                        var serializeAs = JsConfig.TreatEnumAsInteger || (type.Attributes.Safe().Any(x => x.Name == "Flags"))
                            ? "@SerializedName(\"{0}\") ".Fmt(value)
                            : "";

                        sb.AppendLine(value == null
                            ? "{0}{1}".Fmt(name.ToPascalCase(), delim)
                            : serializeAs + "{0}({1}){2}".Fmt(name.ToPascalCase(), value, delim));

                        hasIntValue = hasIntValue || value != null;
                    }

                    if (hasIntValue)
                    {
                        sb.AppendLine();
                        sb.AppendLine("private final int value;");
                        sb.AppendLine("{0}(final int intValue) {{ value = intValue; }}".Fmt(typeName));
                        sb.AppendLine("public int getValue() { return value; }");
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var defType = type.IsInterface()
                    ? "interface"
                    : "class";
                var extends = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    extends.Add(Type(type.Inherits).InheritedType());
                }

                string responseTypeExpression = null;

                var interfaces = new List <string>();
                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        interfaces.Add(implStr);

                        if (implStr.StartsWith("IReturn<"))
                        {
                            var types      = implStr.RightPart('<');
                            var returnType = types.Substring(0, types.Length - 1);

                            //Can't get .class from Generic Type definition
                            responseTypeExpression = returnType.Contains("<")
                                ? "new TypeToken<{0}>(){{}}.getType()".Fmt(returnType)
                                : "{0}.class".Fmt(returnType);
                        }
                    }
                    if (!type.Implements.IsEmpty())
                    {
                        foreach (var interfaceRef in type.Implements)
                        {
                            interfaces.Add(Type(interfaceRef));
                        }
                    }
                }

                var extend = extends.Count > 0
                    ? " extends " + extends[0]
                    : "";

                if (interfaces.Count > 0)
                {
                    extend += " implements " + string.Join(", ", interfaces.ToArray());
                }

                var addPropertyAccessors = Config.AddPropertyAccessors && !type.IsInterface();
                var settersReturnType    = addPropertyAccessors && Config.SettersReturnThis ? typeName : null;

                sb.AppendLine("public static {0} {1}{2}".Fmt(defType, typeName, extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine("public Integer {0} = {1};".Fmt("Version".PropertyStyle(), Config.AddImplicitVersion));

                    if (addPropertyAccessors)
                    {
                        sb.AppendPropertyAccessor("Integer", "Version", settersReturnType);
                    }
                }

                AddProperties(sb, type,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name),
                              addPropertyAccessors: addPropertyAccessors,
                              settersReturnType: settersReturnType);

                if (responseTypeExpression != null)
                {
                    sb.AppendLine("private static Object responseType = {0};".Fmt(responseTypeExpression));
                    sb.AppendLine("public Object getResponseType() { return responseType; }");
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            sb = sb.UnIndent();

            return(lastNS);
        }
예제 #50
0
        public void AddProperties(StringBuilderWrapper sb, MetadataType type,
                                  bool includeResponseStatus,
                                  bool addPropertyAccessors,
                                  string settersReturnType)
        {
            var wasAdded = false;

            var sbInner     = StringBuilderCacheAlt.Allocate();
            var sbAccessors = new StringBuilderWrapper(sbInner);

            if (addPropertyAccessors)
            {
                sbAccessors.AppendLine();
                sbAccessors = sbAccessors.Indent().Indent();
            }

            var dataMemberIndex = 1;

            if (type.Properties != null)
            {
                foreach (var prop in type.Properties)
                {
                    if (wasAdded)
                    {
                        sb.AppendLine();
                    }

                    var propType = Type(prop.Type, prop.GenericArgs);

                    var fieldName    = prop.Name.SafeToken().PropertyStyle();
                    var accessorName = fieldName.ToPascalCase();

                    wasAdded = AppendComments(sb, prop.Description);
                    wasAdded = AppendDataMember(sb, prop.DataMember, dataMemberIndex++) || wasAdded;
                    wasAdded = AppendAttributes(sb, prop.Attributes) || wasAdded;

                    if (!fieldName.IsKeyWord())
                    {
                        sb.AppendLine("public {0} {1} = null;".Fmt(propType, fieldName));
                    }
                    else
                    {
                        var originalName = fieldName;
                        fieldName = Char.ToUpper(fieldName[0]) + fieldName.SafeSubstring(1);
                        sb.AppendLine("@SerializedName(\"{0}\") public {1} {2} = null;".Fmt(originalName, propType, fieldName));
                    }

                    if (addPropertyAccessors)
                    {
                        sbAccessors.AppendPropertyAccessor(propType, fieldName, accessorName, settersReturnType);
                    }
                }
            }

            if (includeResponseStatus)
            {
                if (wasAdded)
                {
                    sb.AppendLine();
                }

                AppendDataMember(sb, null, dataMemberIndex++);
                sb.AppendLine("public ResponseStatus {0} = null;".Fmt(typeof(ResponseStatus).Name.PropertyStyle()));

                if (addPropertyAccessors)
                {
                    sbAccessors.AppendPropertyAccessor("ResponseStatus", "ResponseStatus", settersReturnType);
                }
            }

            if (sbAccessors.Length > 0)
            {
                sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbInner).TrimEnd()); //remove last \n
            }
        }
예제 #51
0
        public TypeDesc GetSystemType()
        {
            MetadataType systemType = _module.Context.SystemModule.GetType("System", "Type");

            return(systemType);
        }
예제 #52
0
        public void AddProperties(StringBuilderWrapper sb, MetadataType type,
                                  bool initCollections, bool includeResponseStatus)
        {
            var wasAdded = false;

            var dataMemberIndex = 1;

            foreach (var prop in type.Properties.Safe())
            {
                if (wasAdded)
                {
                    sb.AppendLine();
                }

                var propTypeName = Type(prop.Type, prop.GenericArgs);
                var propType     = FindType(prop.Type, prop.TypeNamespace, prop.GenericArgs);
                var optional     = "";
                var defaultValue = "";
                if (propTypeName.EndsWith("?"))
                {
                    propTypeName = propTypeName.Substring(0, propTypeName.Length - 1);
                    optional     = "?";
                }
                if (Config.MakePropertiesOptional)
                {
                    optional = "?";
                }

                if (prop.Attributes.Safe().FirstOrDefault(x => x.Name == "Required") != null)
                {
                    optional = "?"; //always use optional
                }

                if (prop.IsArray())
                {
                    optional     = "";
                    defaultValue = " = []";
                }
                else if (initCollections && !prop.GenericArgs.IsEmpty())
                {
                    if (ArrayTypes.Contains(prop.Type))
                    {
                        optional     = "";
                        defaultValue = " = []";
                    }
                    if (DictionaryTypes.Contains(prop.Type))
                    {
                        optional     = "";
                        defaultValue = " = [:]";
                    }
                }

                if (propType.IsInterface() || IgnorePropertyNames.Contains(prop.Name))
                {
                    sb.AppendLine("//{0}:{1} ignored. Swift doesn't support interface properties"
                                  .Fmt(prop.Name.SafeToken().PropertyStyle(), propTypeName));
                    continue;
                }
                else if (IgnorePropertyTypeNames.Contains(propTypeName))
                {
                    sb.AppendLine("//{0}:{1} ignored. Type could not be extended in Swift"
                                  .Fmt(prop.Name.SafeToken().PropertyStyle(), propTypeName));
                    continue;
                }

                wasAdded = AppendComments(sb, prop.Description);
                wasAdded = AppendDataMember(sb, prop.DataMember, dataMemberIndex++) || wasAdded;
                wasAdded = AppendAttributes(sb, prop.Attributes) || wasAdded;

                if (type.IsInterface())
                {
                    sb.AppendLine("var {0}:{1}{2} {{ get set }}".Fmt(
                                      prop.Name.SafeToken().PropertyStyle(), propTypeName, optional));
                }
                else
                {
                    sb.AppendLine("public var {0}:{1}{2}{3}".Fmt(
                                      prop.Name.SafeToken().PropertyStyle(), propTypeName, optional, defaultValue));
                }
            }

            if (includeResponseStatus)
            {
                if (wasAdded)
                {
                    sb.AppendLine();
                }

                AppendDataMember(sb, null, dataMemberIndex++);
                sb.AppendLine("public var {0}:ResponseStatus?".Fmt(typeof(ResponseStatus).Name.PropertyStyle()));
            }
        }
예제 #53
0
        public void AddProperties(StringBuilderWrapper sb, MetadataType type,
            bool initCollections, bool includeResponseStatus)
        {
            var wasAdded = false;

            var dataMemberIndex = 1;
            foreach (var prop in type.Properties.Safe())
            {
                if (wasAdded) sb.AppendLine();

                var propTypeName = Type(prop.Type, prop.GenericArgs);
                var propType = FindType(prop.Type, prop.TypeNamespace, prop.GenericArgs);
                var optional = "";
                var defaultValue = "";
                if (propTypeName.EndsWith("?"))
                {
                    propTypeName = propTypeName.Substring(0, propTypeName.Length - 1);
                    optional = "?";
                }
                if (Config.MakePropertiesOptional)
                {
                    optional = "?";
                }

                if (prop.Attributes.Safe().FirstOrDefault(x => x.Name == "Required") != null)
                {
                    optional = "?"; //always use optional
                }

                if (prop.IsArray())
                {
                    optional = "";
                    defaultValue = " = []";
                }
                else if (initCollections && !prop.GenericArgs.IsEmpty())
                {
                    if (ArrayTypes.Contains(prop.Type))
                    {
                        optional = "";
                        defaultValue = " = []";
                    }
                    if (DictionaryTypes.Contains(prop.Type))
                    {
                        optional = "";
                        defaultValue = " = [:]";
                    }
                }

                if (propType.IsInterface() || IgnorePropertyNames.Contains(prop.Name))
                {
                    sb.AppendLine("//{0}:{1} ignored. Swift doesn't support interface properties"
                        .Fmt(prop.Name.SafeToken().PropertyStyle(), propTypeName));
                    continue;
                }
                else if (IgnorePropertyTypeNames.Contains(propTypeName))
                {
                    sb.AppendLine("//{0}:{1} ignored. Type could not be extended in Swift"
                        .Fmt(prop.Name.SafeToken().PropertyStyle(), propTypeName));
                    continue;
                }

                wasAdded = AppendDataMember(sb, prop.DataMember, dataMemberIndex++);
                wasAdded = AppendAttributes(sb, prop.Attributes) || wasAdded;

                if (type.IsInterface())
                {
                    sb.AppendLine("var {0}:{1}{2} {{ get set }}".Fmt(
                        prop.Name.SafeToken().PropertyStyle(), propTypeName, optional));
                }
                else
                {
                    sb.AppendLine("public var {0}:{1}{2}{3}".Fmt(
                        prop.Name.SafeToken().PropertyStyle(), propTypeName, optional, defaultValue));
                }
            }

            if (includeResponseStatus)
            {
                if (wasAdded) sb.AppendLine();

                AppendDataMember(sb, null, dataMemberIndex++);
                sb.AppendLine("public var {0}:ResponseStatus?".Fmt(typeof(ResponseStatus).Name.PropertyStyle()));
            }
        }
예제 #54
0
        protected sealed override void EmitCode(NodeFactory factory, ref X64Emitter encoder, bool relocsOnly)
        {
            // First load the generic context into Arg0.
            EmitLoadGenericContext(factory, ref encoder, relocsOnly);

            switch (_id)
            {
            case ReadyToRunHelperId.GetNonGCStaticBase:
            {
                MetadataType target = (MetadataType)_target;

                if (!factory.TypeSystemContext.HasLazyStaticConstructor(target))
                {
                    EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Result, _lookupSignature, relocsOnly);
                    encoder.EmitRET();
                }
                else
                {
                    EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Arg0, _lookupSignature, relocsOnly);

                    // We need to trigger the cctor before returning the base. It is stored at the beginning of the non-GC statics region.
                    int cctorContextSize = NonGCStaticsNode.GetClassConstructorContextStorageSize(factory.Target, target);

                    AddrMode loadBase = new AddrMode(encoder.TargetRegister.Arg0, null, cctorContextSize, 0, AddrModeSize.Int64);
                    encoder.EmitLEA(encoder.TargetRegister.Result, ref loadBase);

                    AddrMode initialized = new AddrMode(encoder.TargetRegister.Arg0, null, factory.Target.PointerSize, 0, AddrModeSize.Int32);
                    encoder.EmitCMP(ref initialized, 1);
                    encoder.EmitRETIfEqual();

                    encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Result);
                    encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnNonGCStaticBase));
                }
            }
            break;

            case ReadyToRunHelperId.GetGCStaticBase:
            {
                MetadataType target = (MetadataType)_target;

                EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Result, _lookupSignature, relocsOnly);

                AddrMode loadFromResult = new AddrMode(encoder.TargetRegister.Result, null, 0, 0, AddrModeSize.Int64);
                encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromResult);
                encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromResult);

                if (!factory.TypeSystemContext.HasLazyStaticConstructor(target))
                {
                    encoder.EmitRET();
                }
                else
                {
                    // We need to trigger the cctor before returning the base. It is stored at the beginning of the non-GC statics region.
                    GenericLookupResult nonGcRegionLookup = factory.GenericLookup.TypeNonGCStaticBase(target);
                    EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Arg0, nonGcRegionLookup, relocsOnly);

                    AddrMode initialized = new AddrMode(encoder.TargetRegister.Arg0, null, factory.Target.PointerSize, 0, AddrModeSize.Int32);
                    encoder.EmitCMP(ref initialized, 1);
                    encoder.EmitRETIfEqual();

                    encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Result);

                    encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnGCStaticBase));
                }
            }
            break;

            case ReadyToRunHelperId.GetThreadStaticBase:
            {
                MetadataType target = (MetadataType)_target;

                // Look up the index cell
                EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Arg1, _lookupSignature, relocsOnly);

                ISymbolNode helperEntrypoint;
                if (factory.TypeSystemContext.HasLazyStaticConstructor(target))
                {
                    // There is a lazy class constructor. We need the non-GC static base because that's where the
                    // class constructor context lives.
                    GenericLookupResult nonGcRegionLookup = factory.GenericLookup.TypeNonGCStaticBase(target);
                    EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Arg2, nonGcRegionLookup, relocsOnly);

                    helperEntrypoint = factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnThreadStaticBase);
                }
                else
                {
                    helperEntrypoint = factory.HelperEntrypoint(HelperEntrypoint.GetThreadStaticBaseForType);
                }

                // First arg: address of the TypeManager slot that provides the helper with
                // information about module index and the type manager instance (which is used
                // for initialization on first access).
                AddrMode loadFromArg1 = new AddrMode(encoder.TargetRegister.Arg1, null, 0, 0, AddrModeSize.Int64);
                encoder.EmitMOV(encoder.TargetRegister.Arg0, ref loadFromArg1);

                // Second arg: index of the type in the ThreadStatic section of the modules
                AddrMode loadFromArg1AndDelta = new AddrMode(encoder.TargetRegister.Arg1, null, factory.Target.PointerSize, 0, AddrModeSize.Int64);
                encoder.EmitMOV(encoder.TargetRegister.Arg1, ref loadFromArg1AndDelta);

                encoder.EmitJMP(helperEntrypoint);
            }
            break;

            // These are all simple: just get the thing from the dictionary and we're done
            case ReadyToRunHelperId.TypeHandle:
            case ReadyToRunHelperId.MethodDictionary:
            case ReadyToRunHelperId.VirtualCall:
            case ReadyToRunHelperId.ResolveVirtualFunction:
            case ReadyToRunHelperId.MethodEntry:
            {
                EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Result, _lookupSignature, relocsOnly);
                encoder.EmitRET();
            }
            break;

            default:
                throw new NotImplementedException();
            }
        }
예제 #55
0
 internal Metadata(string path, MetadataType type, MetadataFormat format, string version, string schema)
 {
     _path = path;
     Type = type;
     Format = format;
     Version = version;
     Schema = schema;
     State = MetadataState.Initialized;
 }
예제 #56
0
        internal static MarshallerKind GetMarshallerKind(
            TypeDesc type,
            MarshalAsDescriptor marshalAs,
            bool isReturn,
            bool isAnsi,
            MarshallerType marshallerType,
            out MarshallerKind elementMarshallerKind)
        {
            if (type.IsByRef)
            {
                type = type.GetParameterType();
            }
            TypeSystemContext context    = type.Context;
            NativeTypeKind    nativeType = NativeTypeKind.Invalid;
            bool isField = marshallerType == MarshallerType.Field;

            if (marshalAs != null)
            {
                nativeType = (NativeTypeKind)marshalAs.Type;
            }


            elementMarshallerKind = MarshallerKind.Invalid;

            //
            // Determine MarshalerKind
            //
            // This mostly resembles desktop CLR and .NET Native code as we need to match their behavior
            //
            if (type.IsPrimitive)
            {
                switch (type.Category)
                {
                case TypeFlags.Void:
                    return(MarshallerKind.VoidReturn);

                case TypeFlags.Boolean:
                    switch (nativeType)
                    {
                    case NativeTypeKind.Invalid:
                    case NativeTypeKind.Boolean:
                        return(MarshallerKind.Bool);

                    case NativeTypeKind.U1:
                    case NativeTypeKind.I1:
                        return(MarshallerKind.CBool);

                    default:
                        return(MarshallerKind.Invalid);
                    }

                case TypeFlags.Char:
                    switch (nativeType)
                    {
                    case NativeTypeKind.I1:
                    case NativeTypeKind.U1:
                        return(MarshallerKind.AnsiChar);

                    case NativeTypeKind.I2:
                    case NativeTypeKind.U2:
                        return(MarshallerKind.UnicodeChar);

                    case NativeTypeKind.Invalid:
                        if (isAnsi)
                        {
                            return(MarshallerKind.AnsiChar);
                        }
                        else
                        {
                            return(MarshallerKind.UnicodeChar);
                        }

                    default:
                        return(MarshallerKind.Invalid);
                    }

                case TypeFlags.SByte:
                case TypeFlags.Byte:
                    if (nativeType == NativeTypeKind.I1 || nativeType == NativeTypeKind.U1 || nativeType == NativeTypeKind.Invalid)
                    {
                        return(MarshallerKind.BlittableValue);
                    }
                    else
                    {
                        return(MarshallerKind.Invalid);
                    }

                case TypeFlags.Int16:
                case TypeFlags.UInt16:
                    if (nativeType == NativeTypeKind.I2 || nativeType == NativeTypeKind.U2 || nativeType == NativeTypeKind.Invalid)
                    {
                        return(MarshallerKind.BlittableValue);
                    }
                    else
                    {
                        return(MarshallerKind.Invalid);
                    }

                case TypeFlags.Int32:
                case TypeFlags.UInt32:
                    if (nativeType == NativeTypeKind.I4 || nativeType == NativeTypeKind.U4 || nativeType == NativeTypeKind.Invalid)
                    {
                        return(MarshallerKind.BlittableValue);
                    }
                    else
                    {
                        return(MarshallerKind.Invalid);
                    }

                case TypeFlags.Int64:
                case TypeFlags.UInt64:
                    if (nativeType == NativeTypeKind.I8 || nativeType == NativeTypeKind.U8 || nativeType == NativeTypeKind.Invalid)
                    {
                        return(MarshallerKind.BlittableValue);
                    }
                    else
                    {
                        return(MarshallerKind.Invalid);
                    }

                case TypeFlags.IntPtr:
                case TypeFlags.UIntPtr:
                    if (nativeType == NativeTypeKind.Invalid)
                    {
                        return(MarshallerKind.BlittableValue);
                    }
                    else
                    {
                        return(MarshallerKind.Invalid);
                    }

                case TypeFlags.Single:
                    if (nativeType == NativeTypeKind.R4 || nativeType == NativeTypeKind.Invalid)
                    {
                        return(MarshallerKind.BlittableValue);
                    }
                    else
                    {
                        return(MarshallerKind.Invalid);
                    }

                case TypeFlags.Double:
                    if (nativeType == NativeTypeKind.R8 || nativeType == NativeTypeKind.Invalid)
                    {
                        return(MarshallerKind.BlittableValue);
                    }
                    else
                    {
                        return(MarshallerKind.Invalid);
                    }

                default:
                    return(MarshallerKind.Invalid);
                }
            }
            else if (type.IsValueType)
            {
                if (type.IsEnum)
                {
                    return(MarshallerKind.Enum);
                }

                if (InteropTypes.IsSystemDateTime(context, type))
                {
                    if (nativeType == NativeTypeKind.Invalid ||
                        nativeType == NativeTypeKind.Struct)
                    {
                        return(MarshallerKind.OleDateTime);
                    }
                    else
                    {
                        return(MarshallerKind.Invalid);
                    }
                }

                /*
                 *              TODO: Bring HandleRef to CoreLib
                 *              https://github.com/dotnet/corert/issues/2570
                 *
                 *              else if (context.IsHandleRef(type))
                 *              {
                 *                  if (nativeType == NativeType.Invalid)
                 *                      return MarshallerKind.HandleRef;
                 *                  else
                 *                      return MarshallerKind.Invalid;
                 *              }
                 */

                switch (nativeType)
                {
                case NativeTypeKind.Invalid:
                case NativeTypeKind.Struct:
                    if (InteropTypes.IsSystemDecimal(context, type))
                    {
                        return(MarshallerKind.Decimal);
                    }
                    break;

                case NativeTypeKind.LPStruct:
                    if (InteropTypes.IsSystemGuid(context, type) ||
                        InteropTypes.IsSystemDecimal(context, type))
                    {
                        if (isField || isReturn)
                        {
                            return(MarshallerKind.Invalid);
                        }
                        else
                        {
                            return(MarshallerKind.BlittableStructPtr);
                        }
                    }
                    break;

                default:
                    return(MarshallerKind.Invalid);
                }

                if (type is MetadataType)
                {
                    MetadataType metadataType = (MetadataType)type;
                    // the struct type need to be either sequential or explicit. If it is
                    // auto layout we will throw exception.
                    if (!metadataType.IsSequentialLayout && !metadataType.IsExplicitLayout)
                    {
                        throw new InvalidProgramException("The specified structure " + metadataType.Name + " has invalid StructLayout information. It must be either Sequential or Explicit.");
                    }
                }

                if (MarshalHelpers.IsBlittableType(type))
                {
                    return(MarshallerKind.BlittableStruct);
                }
                else
                {
                    return(MarshallerKind.Struct);
                }
            }
            else                  // !ValueType
            {
                if (type.Category == TypeFlags.Class)
                {
                    if (type.IsString)
                    {
                        switch (nativeType)
                        {
                        case NativeTypeKind.LPWStr:
                            return(MarshallerKind.UnicodeString);

                        case NativeTypeKind.LPStr:
                            return(MarshallerKind.AnsiString);

                        case NativeTypeKind.LPTStr:
                            return(MarshallerKind.UnicodeString);

                        case NativeTypeKind.ByValTStr:
                            if (isAnsi)
                            {
                                elementMarshallerKind = MarshallerKind.AnsiChar;
                                return(MarshallerKind.ByValAnsiString);
                            }
                            else
                            {
                                elementMarshallerKind = MarshallerKind.UnicodeChar;
                                return(MarshallerKind.ByValUnicodeString);
                            }

                        case NativeTypeKind.Invalid:
                            if (isAnsi)
                            {
                                return(MarshallerKind.AnsiString);
                            }
                            else
                            {
                                return(MarshallerKind.UnicodeString);
                            }

                        default:
                            return(MarshallerKind.Invalid);
                        }
                    }
                    else if (type.IsDelegate)
                    {
                        if (nativeType == NativeTypeKind.Invalid || nativeType == NativeTypeKind.Func)
                        {
                            return(MarshallerKind.FunctionPointer);
                        }
                        else
                        {
                            return(MarshallerKind.Invalid);
                        }
                    }
                    else if (type.IsObject)
                    {
                        if (nativeType == NativeTypeKind.Invalid)
                        {
                            return(MarshallerKind.Variant);
                        }
                        else
                        {
                            return(MarshallerKind.Invalid);
                        }
                    }
                    else if (InteropTypes.IsStringBuilder(context, type))
                    {
                        switch (nativeType)
                        {
                        case NativeTypeKind.Invalid:
                            if (isAnsi)
                            {
                                return(MarshallerKind.AnsiStringBuilder);
                            }
                            else
                            {
                                return(MarshallerKind.UnicodeStringBuilder);
                            }

                        case NativeTypeKind.LPStr:
                            return(MarshallerKind.AnsiStringBuilder);

                        case NativeTypeKind.LPWStr:
                            return(MarshallerKind.UnicodeStringBuilder);

                        default:
                            return(MarshallerKind.Invalid);
                        }
                    }
                    else if (InteropTypes.IsSafeHandle(context, type))
                    {
                        if (nativeType == NativeTypeKind.Invalid)
                        {
                            return(MarshallerKind.SafeHandle);
                        }
                        else
                        {
                            return(MarshallerKind.Invalid);
                        }
                    }

                    /*
                     *                  TODO: Bring CriticalHandle to CoreLib
                     *                  https://github.com/dotnet/corert/issues/2570
                     *
                     *                  else if (InteropTypes.IsCriticalHandle(context, type))
                     *                  {
                     *                      if (nativeType != NativeType.Invalid || isField)
                     *                      {
                     *                          return MarshallerKind.Invalid;
                     *                      }
                     *                      else
                     *                      {
                     *                          return MarshallerKind.CriticalHandle;
                     *                      }
                     *                  }
                     */
                    return(MarshallerKind.Invalid);
                }
                else if (InteropTypes.IsSystemArray(context, type))
                {
                    return(MarshallerKind.Invalid);
                }
                else if (type.IsSzArray)
                {
                    if (nativeType == NativeTypeKind.Invalid)
                    {
                        nativeType = NativeTypeKind.Array;
                    }

                    switch (nativeType)
                    {
                    case NativeTypeKind.Array:
                    {
                        if (isField || isReturn)
                        {
                            return(MarshallerKind.Invalid);
                        }

                        var arrayType = (ArrayType)type;

                        elementMarshallerKind = GetArrayElementMarshallerKind(
                            arrayType,
                            marshalAs,
                            isAnsi);

                        // If element is invalid type, the array itself is invalid
                        if (elementMarshallerKind == MarshallerKind.Invalid)
                        {
                            return(MarshallerKind.Invalid);
                        }

                        if (elementMarshallerKind == MarshallerKind.AnsiChar)
                        {
                            return(MarshallerKind.AnsiCharArray);
                        }
                        else if (elementMarshallerKind == MarshallerKind.UnicodeChar ||         // Arrays of unicode char should be marshalled as blittable arrays
                                 elementMarshallerKind == MarshallerKind.Enum ||
                                 elementMarshallerKind == MarshallerKind.BlittableValue)
                        {
                            return(MarshallerKind.BlittableArray);
                        }
                        else
                        {
                            return(MarshallerKind.Array);
                        }
                    }

                    case NativeTypeKind.ByValArray:             // fix sized array
                    {
                        var arrayType = (ArrayType)type;
                        elementMarshallerKind = GetArrayElementMarshallerKind(
                            arrayType,
                            marshalAs,
                            isAnsi);

                        // If element is invalid type, the array itself is invalid
                        if (elementMarshallerKind == MarshallerKind.Invalid)
                        {
                            return(MarshallerKind.Invalid);
                        }

                        if (elementMarshallerKind == MarshallerKind.AnsiChar)
                        {
                            return(MarshallerKind.ByValAnsiCharArray);
                        }
                        else
                        {
                            return(MarshallerKind.ByValArray);
                        }
                    }

                    default:
                        return(MarshallerKind.Invalid);
                    }
                }
                else if (type.Category == TypeFlags.Pointer)
                {
                    //
                    // @TODO - add checks for the pointee type in case the pointee type is not blittable
                    // C# already does this and will emit compilation errors (can't declare pointers to
                    // managed type).
                    //
                    if (nativeType == NativeTypeKind.Invalid)
                    {
                        return(MarshallerKind.BlittableValue);
                    }
                    else
                    {
                        return(MarshallerKind.Invalid);
                    }
                }
            }

            return(MarshallerKind.Invalid);
        }
예제 #57
0
 public override void SetMetadata(MetadataType type, IEnumerable<string> value)
 {
     parsedFile.Metadata[type] = value.ToList();
 }
예제 #58
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            if (type == null || (type.Namespace != null && type.Namespace.StartsWith("System")))
            {
                return(lastNS);
            }

            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("enum {0}".Fmt(Type(type.Name, type.GenericArgs)));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null
                            ? "{0},".Fmt(name.PropertyStyle())
                            : "{0} = {1},".Fmt(name.PropertyStyle(), value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var extends = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    extends.Add(Type(type.Inherits).InheritedType());
                }

                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        extends.Add(implStr);
                    }
                }

                var extend = extends.Count > 0
                    ? " extends " + (string.Join(", ", extends.ToArray()))
                    : "";

                sb.AppendLine("interface {0}{1}".Fmt(Type(type.Name, type.GenericArgs), extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsOperation;
                if (addVersionInfo)
                {
                    sb.AppendLine("{0}:number; //{1}".Fmt("Version".PropertyStyle(), Config.AddImplicitVersion));
                }

                AddProperties(sb, type);

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            sb = sb.UnIndent();

            return(lastNS);
        }
예제 #59
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
            CreateTypeOptions options)
        {
            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            var typeName = Type(type.Name, type.GenericArgs);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("public static enum {0}".Fmt(typeName));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    var hasIntValue = false;
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;

                        var delim = i == type.EnumNames.Count - 1 ? ";" : ",";
                        var serializeAs = JsConfig.TreatEnumAsInteger || (type.Attributes.Safe().Any(x => x.Name == "Flags"))
                            ? "@SerializedName(\"{0}\") ".Fmt(value)
                            : "";

                        sb.AppendLine(value == null
                            ? "{0}{1}".Fmt(name.ToPascalCase(), delim)
                            : serializeAs + "{0}({1}){2}".Fmt(name.ToPascalCase(), value, delim));

                        hasIntValue = hasIntValue || value != null;
                    }

                    if (hasIntValue)
                    {
                        sb.AppendLine();
                        sb.AppendLine("private final int value;");
                        sb.AppendLine("{0}(final int intValue) {{ value = intValue; }}".Fmt(typeName));
                        sb.AppendLine("public int getValue() { return value; }");
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var defType = type.IsInterface()
                    ? "interface"
                    : "class";
                var extends = new List<string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                    extends.Add(Type(type.Inherits).InheritedType());

                string responseTypeExpression = null;

                var interfaces = new List<string>();
                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        interfaces.Add(implStr);

                        if (implStr.StartsWith("IReturn<"))
                        {
                            var types = implStr.RightPart('<');
                            var returnType = types.Substring(0, types.Length - 1);

                            //Can't get .class from Generic Type definition
                            responseTypeExpression = returnType.Contains("<")
                                ? "new TypeToken<{0}>(){{}}.getType()".Fmt(returnType)
                                : "{0}.class".Fmt(returnType);
                        }
                    }
                    if (!type.Implements.IsEmpty())
                    {
                        foreach (var interfaceRef in type.Implements)
                        {
                            interfaces.Add(Type(interfaceRef));
                        }
                    }
                }

                var extend = extends.Count > 0
                    ? " extends " + extends[0]
                    : "";

                if (interfaces.Count > 0)
                    extend += " implements " + string.Join(", ", interfaces.ToArray());

                var addPropertyAccessors = Config.AddPropertyAccessors && !type.IsInterface();
                var settersReturnType = addPropertyAccessors && Config.SettersReturnThis ? typeName : null;

                sb.AppendLine("public static {0} {1}{2}".Fmt(defType, typeName, extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine("public Integer {0} = {1};".Fmt("Version".PropertyStyle(), Config.AddImplicitVersion));

                    if (addPropertyAccessors)
                        sb.AppendPropertyAccessor("Integer", "Version", settersReturnType);
                }

                AddProperties(sb, type,
                    includeResponseStatus: Config.AddResponseStatus && options.IsResponse
                        && type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name),
                    addPropertyAccessors: addPropertyAccessors,
                    settersReturnType: settersReturnType);

                if (responseTypeExpression != null)
                {
                    sb.AppendLine("private static Object responseType = {0};".Fmt(responseTypeExpression));
                    sb.AppendLine("public Object getResponseType() { return responseType; }");
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            sb = sb.UnIndent();

            return lastNS;
        }
예제 #60
0
        public string GetCode(MetadataTypes metadata, IRequest request, INativeTypesMetadata nativeTypes)
        {
            var namespaces = new HashSet <string>();

            Config.DefaultNamespaces.Each(x => namespaces.Add(x));

            var typeNamespaces = new HashSet <string>();

            metadata.Types.Each(x => typeNamespaces.Add(x.Namespace));
            metadata.Operations.Each(x => typeNamespaces.Add(x.Request.Namespace));

            // Look first for shortest Namespace ending with `ServiceModel` convention, else shortest ns
            var globalNamespace = Config.GlobalNamespace
                                  ?? typeNamespaces.Where(x => x.EndsWith("ServiceModel"))
                                  .OrderBy(x => x).FirstOrDefault()
                                  ?? typeNamespaces.OrderBy(x => x).First();

            Func <string, string> defaultValue = k =>
                                                 request.QueryString[k].IsNullOrEmpty() ? "//" : "";

            var sb = new StringBuilderWrapper(new StringBuilder());

            sb.AppendLine("/* Options:");
            sb.AppendLine("Date: {0}".Fmt(DateTime.Now.ToString("s").Replace("T", " ")));
            sb.AppendLine("Version: {0}".Fmt(metadata.Version));
            sb.AppendLine("BaseUrl: {0}".Fmt(Config.BaseUrl));
            sb.AppendLine();
            sb.AppendLine("{0}GlobalNamespace: {1}".Fmt(defaultValue("GlobalNamespace"), Config.GlobalNamespace));
            sb.AppendLine("{0}AddServiceStackTypes: {1}".Fmt(defaultValue("AddServiceStackTypes"), Config.AddServiceStackTypes));
            sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(defaultValue("AddResponseStatus"), Config.AddResponseStatus));
            sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(defaultValue("AddImplicitVersion"), Config.AddImplicitVersion));

            sb.AppendLine("*/");
            sb.AppendLine();

            string lastNS = null;

            var existingOps = new HashSet <string>();

            var requestTypes    = metadata.Operations.Select(x => x.Request).ToHashSet();
            var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request);
            var responseTypes   = metadata.Operations
                                  .Where(x => x.Response != null)
                                  .Select(x => x.Response).ToHashSet();
            var types = metadata.Types.ToHashSet();

            var allTypes = new List <MetadataType>();

            allTypes.AddRange(types);
            allTypes.AddRange(responseTypes);
            allTypes.AddRange(requestTypes);

            //TypeScript doesn't support reusing same type name with different generic airity
            var conflictPartialNames = allTypes.Map(x => x.Name).Distinct()
                                       .GroupBy(g => g.SplitOnFirst('`')[0])
                                       .Where(g => g.Count() > 1)
                                       .Select(g => g.Key)
                                       .ToList();

            this.conflictTypeNames = allTypes
                                     .Where(x => conflictPartialNames.Any(name => x.Name.StartsWith(name)))
                                     .Map(x => x.Name);

            sb.AppendLine("declare module {0}".Fmt(globalNamespace.SafeToken()));
            sb.AppendLine("{");

            //ServiceStack core interfaces
            foreach (var type in allTypes)
            {
                var fullTypeName = type.GetFullName();
                if (requestTypes.Contains(type))
                {
                    if (!existingOps.Contains(fullTypeName))
                    {
                        MetadataType          response = null;
                        MetadataOperationType operation;
                        if (requestTypesMap.TryGetValue(type, out operation))
                        {
                            response = operation.Response;
                        }

                        lastNS = AppendType(ref sb, type, lastNS,
                                            new CreateTypeOptions
                        {
                            ImplementsFn = () =>
                            {
                                if (!Config.AddReturnMarker &&
                                    !type.ReturnVoidMarker &&
                                    type.ReturnMarkerTypeName == null)
                                {
                                    return(null);
                                }

                                if (type.ReturnVoidMarker)
                                {
                                    return("IReturnVoid");
                                }
                                if (type.ReturnMarkerTypeName != null)
                                {
                                    return(Type("IReturn`1", new[] { Type(type.ReturnMarkerTypeName) }));
                                }
                                return(response != null
                                        ? Type("IReturn`1", new[] { Type(type.Name, type.GenericArgs) })
                                        : null);
                            },
                            IsRequest = true,
                        });

                        existingOps.Add(fullTypeName);
                    }
                }
                else if (responseTypes.Contains(type))
                {
                    if (!existingOps.Contains(fullTypeName) &&
                        !Config.IgnoreTypesInNamespaces.Contains(type.Namespace))
                    {
                        lastNS = AppendType(ref sb, type, lastNS,
                                            new CreateTypeOptions
                        {
                            IsResponse = true,
                        });

                        existingOps.Add(fullTypeName);
                    }
                }
                else if (types.Contains(type) && !existingOps.Contains(fullTypeName))
                {
                    lastNS = AppendType(ref sb, type, lastNS,
                                        new CreateTypeOptions {
                        IsType = true
                    });
                }
            }

            sb.AppendLine();
            sb.AppendLine("}");

            return(sb.ToString());
        }