public void Testing( KnownTypes sut )
		{
			var parameter = typeof(Class);

			var items = sut.Get( parameter );

			Assert.NotEmpty( items );

			Assert.All( items, item => Assert.True( parameter.IsAssignableFrom( item ) ) );
		}
        private static TypeSyntax FixMethodReturnType(
            IMethodSymbol methodSymbol,
            TypeSyntax returnTypeSyntax,
            KnownTypes knownTypes
            )
        {
            var newReturnType = returnTypeSyntax;

            var returnType = methodSymbol.ReturnType;

            if (returnType.OriginalDefinition.Equals(knownTypes._taskType))
            {
                // If the return type is Task, then make the new return type "void".
                newReturnType = SyntaxFactory
                                .PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword))
                                .WithTriviaFrom(returnTypeSyntax);
            }
            else if (returnType.OriginalDefinition.Equals(knownTypes._taskOfTType))
            {
                // If the return type is Task<T>, then make the new return type "T".
                newReturnType = returnType.GetTypeArguments()[0]
                                .GenerateTypeSyntax()
                                .WithTriviaFrom(returnTypeSyntax);
            }
            else if (returnType.OriginalDefinition.Equals(knownTypes._iAsyncEnumerableOfTTypeOpt))
            {
                // If the return type is IAsyncEnumerable<T>, then make the new return type IEnumerable<T>.
                newReturnType = knownTypes._iEnumerableOfTType
                                .Construct(methodSymbol.ReturnType.GetTypeArguments()[0])
                                .GenerateTypeSyntax();
            }
            else if (returnType.OriginalDefinition.Equals(knownTypes._iAsyncEnumeratorOfTTypeOpt))
            {
                // If the return type is IAsyncEnumerator<T>, then make the new return type IEnumerator<T>.
                newReturnType = knownTypes._iEnumeratorOfTType
                                .Construct(methodSymbol.ReturnType.GetTypeArguments()[0])
                                .GenerateTypeSyntax();
            }

            return(newReturnType);
        }
        private static TypeSyntax FixMethodReturnType(
            bool keepVoid, IMethodSymbol methodSymbol, TypeSyntax returnTypeSyntax,
            KnownTypes knownTypes)
        {
            var newReturnType = returnTypeSyntax.WithAdditionalAnnotations(Formatter.Annotation);

            if (methodSymbol.ReturnsVoid)
            {
                if (!keepVoid)
                {
                    newReturnType = knownTypes._taskType.GenerateTypeSyntax();
                }
            }
            else
            {
                var returnType = methodSymbol.ReturnType;
                if (IsIEnumerable(returnType, knownTypes) && IsIterator(methodSymbol))
                {
                    newReturnType = knownTypes._iAsyncEnumerableOfTTypeOpt is null
                        ? MakeGenericType("IAsyncEnumerable", methodSymbol.ReturnType)
                        : knownTypes._iAsyncEnumerableOfTTypeOpt.Construct(methodSymbol.ReturnType.GetTypeArguments()[0]).GenerateTypeSyntax();
                }
                else if (IsIEnumerator(returnType, knownTypes) && IsIterator(methodSymbol))
                {
                    newReturnType = knownTypes._iAsyncEnumeratorOfTTypeOpt is null
                        ? MakeGenericType("IAsyncEnumerator", methodSymbol.ReturnType)
                        : knownTypes._iAsyncEnumeratorOfTTypeOpt.Construct(methodSymbol.ReturnType.GetTypeArguments()[0]).GenerateTypeSyntax();
                }
                else if (IsIAsyncEnumerableOrEnumerator(returnType, knownTypes))
                {
                    // Leave the return type alone
                }
                else if (!IsTaskLike(returnType, knownTypes))
                {
                    // If it's not already Task-like, then wrap the existing return type
                    // in Task<>.
                    newReturnType = knownTypes._taskOfTType.Construct(methodSymbol.ReturnType).GenerateTypeSyntax();
                }
            }

            return(newReturnType.WithTriviaFrom(returnTypeSyntax).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation));
Exemple #4
0
        List <DataMemberInfo> GetMembers(Type type, QName qname, bool declared_only)
        {
            List <DataMemberInfo> data_members = new List <DataMemberInfo> ();
            BindingFlags          flags        = AllInstanceFlags;

            if (declared_only)
            {
                flags |= BindingFlags.DeclaredOnly;
            }

            foreach (PropertyInfo pi in type.GetProperties(flags))
            {
                DataMemberAttribute dma =
                    GetDataMemberAttribute(pi);
                if (dma == null)
                {
                    continue;
                }
                KnownTypes.Add(pi.PropertyType);
                var map = KnownTypes.FindUserMap(pi.PropertyType);
                if (!pi.CanRead || (!pi.CanWrite && !(map is ICollectionTypeMap)))
                {
                    throw new InvalidDataContractException(String.Format(
                                                               "DataMember property '{0}' on type '{1}' must have both getter and setter.", pi, pi.DeclaringType));
                }
                data_members.Add(CreateDataMemberInfo(dma, pi, pi.PropertyType, KnownTypeCollection.GetStaticQName(pi.DeclaringType).Namespace));
            }

            foreach (FieldInfo fi in type.GetFields(flags))
            {
                DataMemberAttribute dma =
                    GetDataMemberAttribute(fi);
                if (dma == null)
                {
                    continue;
                }
                data_members.Add(CreateDataMemberInfo(dma, fi, fi.FieldType, KnownTypeCollection.GetStaticQName(fi.DeclaringType).Namespace));
            }

            return(data_members);
        }
Exemple #5
0
        internal void Initialize()
        {
            Type type = RuntimeType;
            List <DataMemberInfo> members = new List <DataMemberInfo> ();

            object [] atts = type.GetCustomAttributes(
                typeof(DataContractAttribute), false);
            IsReference = atts.Length > 0 ? (((DataContractAttribute)atts [0]).IsReference) : false;

            while (type != null)
            {
                QName qname = KnownTypes.GetQName(type);

                members = GetMembers(type, qname, true);
                members.Sort(DataMemberInfo.DataMemberInfoComparer.Instance);
                Members.InsertRange(0, members);
                members.Clear();

                type = type.BaseType;
            }
        }
Exemple #6
0
        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.EnableConcurrentExecution();
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            analysisContext.RegisterCompilationStartAction(
                (context) =>
            {
                var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(context.Compilation);
                var knownTypes            = new KnownTypes(wellKnownTypeProvider);

                if (knownTypes.ICollectionType == null ||
                    knownTypes.GenericICollectionType == null ||
                    knownTypes.ArrayType == null)
                {
                    return;
                }

                context.RegisterSymbolAction(c => AnalyzeSymbol(c, knownTypes), SymbolKind.Property);
            });
        }
 public bool SavePackage(BaseChangePackage package, string location = null)
 {
     if (package == null)
     {
         return(true);
     }
     location = location == null ? package.PackageLocation : location;
     if (location == null)
     {
         return(SavePackageAs(package));
     }
     else
     {
         XmlSerializer ser    = new XmlSerializer(typeof(BaseChangePackage), KnownTypes.ToArray());
         TextWriter    writer = new StreamWriter(location);
         ser.Serialize(writer, package);
         writer.Close();
         package.HasUnsavedChanges = false;
         return(true);
     }
 }
        public BaseChangePackage LoadPackage(string location = null)
        {
            BaseChangePackage result = null;

            if (location == null)
            {
                using (var fd = new System.Windows.Forms.OpenFileDialog())
                {
                    fd.DefaultExt  = "ecp";
                    fd.Filter      = "EZChange Files (*.ecp)|*.ecp|All files (*.*)|*.*";
                    fd.FilterIndex = 1;
                    if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        location = fd.FileName;
                    }
                    else
                    {
                        return(result);
                    }
                }
            }
            if (location != null)
            {
                XmlSerializer ser    = new XmlSerializer(typeof(BaseChangePackage), KnownTypes.ToArray());
                TextReader    reader = new StreamReader(location);
                result = (BaseChangePackage)ser.Deserialize(reader);
                result.PackageLocation = location;
                result.InitializeComponents();
                reader.Close();
            }
            if (result != null)
            {
                foreach (var s in result.Solutions)
                {
                    s.Package = result;
                }
            }

            return(result);
        }
        private bool TryGetBamlAssembly(Int16 assemblyId, out BamlAssembly bamlAssembly)
        {
            lock (_syncObject)
            {
                if (assemblyId >= 0 && assemblyId < _bamlAssembly.Count)
                {
                    bamlAssembly = _bamlAssembly[assemblyId];
                    return(true);
                }
            }

            Assembly assembly = KnownTypes.GetKnownAssembly(assemblyId);

            if (assembly != null)
            {
                bamlAssembly = new BamlAssembly(assembly);
                return(true);
            }

            bamlAssembly = null;
            return(false);
        }
Exemple #10
0
        public static object ReadValue(DataStream stream)
        {
            KnownTypes type = (KnownTypes)stream.ReadByte();

            switch (type)
            {
            case KnownTypes.Double:
                return(stream.ReadDouble());

            case KnownTypes.Bool:
                return(stream.ReadBool());

            case KnownTypes.String:
                return(ReadString(stream));

            case KnownTypes.Date:
                return(stream.ReadBytes(10));

            case KnownTypes.Null:
            case KnownTypes.Undefined:
            case KnownTypes.Unsupported:
                return(type);

            case KnownTypes.Array:
                return(ReadArray(stream));

            case KnownTypes.MixedArray:
                return(ReadMixedArray(stream));

            case KnownTypes.Object:
                return(ReadObject(stream));

            case KnownTypes.ObjectEnd:
                return(null);

            default:
                throw new InvalidOperationException("Invalid or unsupported data type: " + type);
            }
        }
        private string ResolveFullName(string type)
        {
            if (genericTypes == null)
            {
                genericTypes = GetGenericParametersInContext(Context);
            }

            if (genericTypes.TryGetValue(type.ToString(), out var genericType))
            {
                return(genericType);
            }

            if (Usings == null || KnownTypes == null)
            {
                return(type);
            }

            return(Usings
                   .Select(x => x + "." + type)
                   .FirstOrDefault(x => KnownTypes.Contains(x)) ??
                   type);
        }
Exemple #12
0
        public void Entity(Type type, bool ignoreUnsupported = false)
        {
            type = type ?? throw new ArgumentNullException(nameof(type));
            if (!typeof(IOgmEntity).IsAssignableFrom(type))
            {
                throw new ArgumentException($"must be assignable to {typeof(IOgmEntity).FullName}", nameof(type));
            }

            if (type.IsSealed)
            {
                throw new ArgumentException("Unable to manage sealed types.", nameof(type));
            }
            if (type.GetMethods().Where(p => p.Name != nameof(Object.GetType) && !p.IsSpecialName).Any(p => !p.IsVirtual))
            {
                throw new ArgumentException("Unable to manage type with non virtual methods", nameof(type));
            }

            List <PropertyInfo> unsupported = type.GetProperties()
                                              .Where(
                p =>
                (
                    !typeof(IOgmConnection).IsAssignableFrom(type) ||
                    (p.Name != nameof(IOgmConnection.Source) && p.Name != nameof(IOgmConnection.Destination))
                ) && !IsGraphProperty(p)
                ).ToList();

            if (unsupported.Count > 0 && !ignoreUnsupported)
            {
                throw new ArgumentException($"Unable to manage type with non virtual properties or properties no deriving from {typeof(IOgmEntity).FullName} or compatible with {typeof(ICollection<IOgmEntity>).FullName}. Set '{nameof(ignoreUnsupported)}' parameter in order to ignore them.");
            }

            if (!KnownTypes.ContainsKey(type))
            {
                KnownTypes.Add(type, new KnownTypeDescriptor());
            }

            KnownTypes[type].IgnoredProperties.AddRange(unsupported);
        }
 static SuspensionManager()
 {
     // Add known types for serialisation
     KnownTypes.Add(typeof(Dictionary <string, object>));
     KnownTypes.Add(typeof(Dictionary <string, Dictionary <string, object> >));
     KnownTypes.Add(typeof(Dictionary <string, Dictionary <string, Dictionary <string, object> > >));
     KnownTypes.Add(typeof(LayoutAwarePage.ObservableDictionary <string, object>));
     KnownTypes.Add(typeof(LayoutAwarePage.ObservableDictionary <string, Dictionary <string, object> >));
     KnownTypes.Add(typeof(LayoutAwarePage.ObservableDictionary <string, Dictionary <string, Dictionary <string, object> > >));
     KnownTypes.Add(typeof(EmailFlags));
     KnownTypes.Add(typeof(KeyValuePair <string, AccountSettingsData>));
     KnownTypes.Add(typeof(Dictionary <string, AccountSettingsData>));
     KnownTypes.Add(typeof(KeyValuePair <AccountSettingsData, ObservableCollection <MailboxListViewItem> >?));
     KnownTypes.Add(typeof(MailboxListViewItem));
     KnownTypes.Add(typeof(MailboxUnreadEmailCount));
     KnownTypes.Add(typeof(NotifyCollectionChangedEventHandler));
     KnownTypes.Add(typeof(MailHeaderDictionary));
     KnownTypes.Add(typeof(List <object>));
     KnownTypes.Add(typeof(MailHeader));
     KnownTypes.Add(typeof(PopMessage));
     KnownTypes.Add(typeof(ImapMessage));
     KnownTypes.Add(typeof(MessageNavigationContext));
 }
Exemple #14
0
        public KnownType GetTypeByName(string name)
        {
            if (TypesLookupCache.ContainsKey(name))
            {
                return(TypesLookupCache[name]);
            }

            var patterns = WholeTypeCache.GetValueOrCompute(name, typeName => InternalGetTypeForName(typeName))
                           ?.PatternsRegexps;

            var result = KnownTypes.FirstOrDefault(c => c.SkriptRepresentations.Contains(name)) ??
                         KnownTypes.FirstOrDefault(t =>
                                                   patterns != null
                                 ? t.SkriptRepresentations.Any(r => patterns.Any(p => p.IsMatch(r)))
                                 : t.SkriptRepresentations.Contains(name));

            if (result != null)
            {
                TypesLookupCache[name] = result;
            }

            return(result);
        }
        internal string GetString(Int16 stringId)
        {
            string result;

            lock (_syncObject)
            {
                if (stringId >= 0 && stringId < _bamlString.Count)
                {
                    result = _bamlString[stringId];
                }
                else
                {
                    result = KnownTypes.GetKnownString(stringId);
                }
            }

            if (result == null)
            {
                throw new KeyNotFoundException();
            }

            return(result);
        }
        private async Task<Solution> RemoveAsyncTokenAsync(
            Document document, IMethodSymbol methodSymbolOpt, SyntaxNode node, CancellationToken cancellationToken)
        {
            var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
            var knownTypes = new KnownTypes(compilation);

            var annotation = new SyntaxAnnotation();
            var newNode = RemoveAsyncTokenAndFixReturnType(methodSymbolOpt, node, knownTypes)
                .WithAdditionalAnnotations(Formatter.Annotation, annotation);

            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var newRoot = root.ReplaceNode(node, newNode);

            var newDocument = document.WithSyntaxRoot(newRoot);
            var newSolution = newDocument.Project.Solution;

            if (methodSymbolOpt == null)
            {
                return newSolution;
            }

            return await RemoveAwaitFromCallersAsync(
                newDocument, annotation, cancellationToken).ConfigureAwait(false);
        }
Exemple #17
0
        public Type[] MatchTypes(string name, int gen)
        {
            if (gen > 0)
            {
                name += "`" + gen;
            }

            if (TypesUtil.PRIMITIVE_TYPES.ContainsKey(name))
            {
                return new[] { TypesUtil.PRIMITIVE_TYPES[name] }
            }
            ;
            var t1 = KnownTypes.Where(i => i.FullName == name).ToArray();

            if (t1.Length == 1)
            {
                return(t1);
            }
            if (t1.Length > 1)
            {
                throw new Exception("pink sparrow");
            }

            var fullNames = _importedNamespaces.Select(i => i.Name + "." + name).Distinct().ToList();

            if (!string.IsNullOrEmpty(_currentNamespace))
            {
                fullNames.Add(_currentNamespace + "." + name);
            }
            var types = (from fullname in fullNames.Distinct()
                         join type in KnownTypes
                         on fullname equals type.FullName
                         select type).ToArray();

            return(types);
        }
        /// <summary>
        /// Starts a TCP server and listens for incoming <see cref="TcpConnection"/>s.
        /// </summary>
        public async Task StartTCPListener()
        {
            if (IsTCPOnline)
            {
                return;
            }

            tcpListener = new TcpListener(System.Net.IPAddress.Parse(IPAddress), Port);
            tcpListener.Server.DualMode = true;
            IsTCPOnline = !IsTCPOnline;
            tcpListener.Start();

            try
            {
                while (IsTCPOnline)
                {
                    TcpClient tcpClient = await tcpListener.AcceptTcpClientAsync();

                    TcpConnection tcpConnection = CreateTcpConnection(tcpClient);
                    tcpConnection.NetworkConnectionClosed += connectionClosed;
                    tcpConnection.ConnectionEstablished   += udpConnectionReceived;
                    connections.GetOrAdd(tcpConnection, new List <UdpConnection>());

                    //Inform all subscribers.
                    if (connectionEstablished != null &&
                        connectionEstablished.GetInvocationList().Length > 0)
                    {
                        connectionEstablished(tcpConnection, ConnectionType.TCP);
                    }

                    KnownTypes.ForEach(tcpConnection.AddExternalPackets);
                }
            }
            //The TCP-Listener has been shut down.
            catch (ObjectDisposedException) { }
        }
Exemple #19
0
 private static bool IsSafeTypeConstraint(Type type)
 {
     if (type == null)
     {
         return(true);
     }
     if (type.IsArray)
     {
         return(IsSafeTypeConstraint(type.GetElementType()));
     }
     return(type.Equals(typeof(Hashtable)) || (type.Equals(typeof(SwitchParameter)) || (type.Equals(typeof(PSCredential)) || (type.Equals(typeof(SecureString)) || (KnownTypes.GetTypeSerializationInfo(type) != null)))));
 }
        private ParameterInfo ResolveParameter(CXType originalType, string name = null, int index = 0)
        {
            string renamed;
            var    type = originalType;

            if (type.kind == CXTypeKind.CXType_FunctionProto)
            {
                throw new NotImplementedException();
            }
            if (type.kind == CXTypeKind.CXType_FunctionNoProto)
            {
                throw new NotImplementedException();
            }
            var typeKind = CanonizeType(ref type, out var typeDeclCursor);

            if (typeKind == CXTypeKind.CXType_Pointer)
            {
                var pointeeType = clang.getPointeeType(type);
                if (clang.getFunctionTypeCallingConv(pointeeType) != CXCallingConv.CXCallingConv_Invalid)
                {
                    var delegateTypeName     = originalType.ToString();
                    var possibleDelegateType = Module.GetType(delegateTypeName);
                    if (possibleDelegateType != null)
                    {
                        return(new ParameterInfo(name, possibleDelegateType, index));
                    }

                    return(new ParameterInfo(name,
                                             IncompleteTypeReference.Get(Module, null, delegateTypeName), index));
                }
                var resolvedParameter = ResolveParameter(pointeeType);
                return(new ParameterInfo(name,
                                         resolvedParameter.Type.MakePointerType(), index));
            }
            if (typeKind == CXTypeKind.CXType_DependentSizedArray)
            {
                throw new NotImplementedException();
            }
            if (typeKind == CXTypeKind.CXType_ConstantArray)
            {
                var arraySize         = (int)clang.getArraySize(type);
                var elementType       = clang.getArrayElementType(type);
                var resolvedParameter = ResolveParameter(elementType, name);
                var clrElementType    = resolvedParameter.Type;
                if (clrElementType.IsPointer)
                {
                    clrElementType = Module.TypeSystem.IntPtr;
                }
                var arrayType = resolvedParameter.Type.MakeArrayType();

                if (!PrimitiveUnmanagedTypeMap.TryGetValue(clrElementType.GetRuntimeType(), out var unmanagedType))
                {
                    throw new NotImplementedException();
                }

                return(new ParameterInfo(name,
                                         arrayType, index, ParameterAttributes.None, arraySize));
            }
            if (PrimitiveTypeMap.TryGetValue(typeKind, out var primitiveType))
            {
                if (primitiveType == null)
                {
                    throw new NotImplementedException();
                }
                var originalTypeName = originalType.ToString();
                var typeName         = originalTypeName;

                if (TypeRedirects.TryGetValue(originalTypeName, out renamed))
                {
                    typeName = renamed;
                }
                if (originalType.kind == CXTypeKind.CXType_Typedef)
                {
                    if (KnownTypes.ContainsKey(typeName))
                    {
                        var knownType = Module.GetType(typeName)
                                        ?? Module.GetType(originalTypeName)
                                        ?? throw new NotImplementedException();
                        return(new ParameterInfo(name, knownType, index));
                    }
                }
                else
                {
                    var found = Module.GetType(typeName);
                    if (found != null)
                    {
                        return(new ParameterInfo(name, found, index));
                    }
                }

                return(new ParameterInfo(name, primitiveType.Import(Module), index));
            }

            var typeDeclName = typeDeclCursor.ToString();

            if (TypeRedirects.TryGetValue(typeDeclName, out renamed))
            {
                typeDeclName = renamed;
            }

            var possibleType = Module.GetType(typeDeclName);

            if (possibleType != null)
            {
                return(new ParameterInfo(name, possibleType, index));
            }

            return(new ParameterInfo(name,
                                     IncompleteTypeReference.Get(Module, null, typeDeclName), index));
        }
Exemple #21
0
		public KnownMember(KnownTypes parent, TypeDef declType, string name, TypeDef type) {
			Parent = parent;
			Property = declType.FindProperty(name);
			DeclaringType = declType;
			Name = name;
			Type = type;
		}
Exemple #22
0
		KnownMember InitMember(KnownTypes parent, string name, TypeDef type) {
			return new KnownMember(parent, types[parent], name, type);
		}
Exemple #23
0
        private static void AnalyzeSymbol(SymbolAnalysisContext context, KnownTypes knownTypes)
        {
            RoslynDebug.Assert(knownTypes.ICollectionType != null &&
                               knownTypes.GenericICollectionType != null &&
                               knownTypes.ArrayType != null);

            var property = (IPropertySymbol)context.Symbol;

            // check whether it has a public setter
            IMethodSymbol setter = property.SetMethod;

            if (setter == null || !setter.IsExternallyVisible())
            {
                return;
            }

            // make sure this property is NOT an indexer
            if (property.IsIndexer)
            {
                return;
            }

            // make sure return type is NOT array
            if (Inherits(property.Type, knownTypes.ArrayType))
            {
                return;
            }

            // make sure property type implements ICollection or ICollection<T>
            if (!Inherits(property.Type, knownTypes.ICollectionType) && !Inherits(property.Type, knownTypes.GenericICollectionType))
            {
                return;
            }

            // exclude Immutable collections
            // see https://github.com/dotnet/roslyn-analyzers/issues/1900 for details
            if (!knownTypes.ImmutableInterfaces.IsEmpty &&
                property.Type.AllInterfaces.Any(i => knownTypes.ImmutableInterfaces.Contains(i.OriginalDefinition)))
            {
                return;
            }

            // exclude readonly collections
            if (property.Type.OriginalDefinition.Equals(knownTypes.ReadonlyCollection) ||
                property.Type.OriginalDefinition.Equals(knownTypes.ReadonlyDictionary) ||
                property.Type.OriginalDefinition.Equals(knownTypes.ReadonlyObservableCollection))
            {
                return;
            }

            if (knownTypes.DataMemberAttribute != null)
            {
                // Special case: the DataContractSerializer requires that a public setter exists.
                bool hasDataMemberAttribute = property.GetAttributes().Any(a => a.AttributeClass.Equals(knownTypes.DataMemberAttribute));
                if (hasDataMemberAttribute)
                {
                    return;
                }
            }

            context.ReportDiagnostic(property.CreateDiagnostic(Rule, property.Name));
        }
Exemple #24
0
        private static SyntaxNode FixLocalFunction(IMethodSymbol methodSymbol, LocalFunctionStatementSyntax localFunction, KnownTypes knownTypes)
        {
            var newReturnType = FixMethodReturnType(methodSymbol, localFunction.ReturnType, knownTypes);
            var newModifiers  = FixMethodModifiers(localFunction.Modifiers, ref newReturnType);

            return(localFunction.WithReturnType(newReturnType).WithModifiers(newModifiers));
        }
Exemple #25
0
 public TypesManager()
 {
     KnownTypes.Add(typeof(Entities.OgmConnection), new KnownTypeDescriptor());
     KnownTypes[typeof(Entities.OgmConnection)].IgnoredProperties.Add(typeof(Entities.IOgmConnection).GetProperty(nameof(Entities.IOgmConnection.Source)));
     KnownTypes[typeof(Entities.OgmConnection)].IgnoredProperties.Add(typeof(Entities.IOgmConnection).GetProperty(nameof(Entities.IOgmConnection.Destination)));
 }
		string Deserialize(XamlContext ctx, XElement elem, KnownTypes ser, byte[] value) {
			using (BinaryReader reader = new BinaryReader(new MemoryStream(value))) {
				switch (ser) {
					case KnownTypes.DependencyPropertyConverter: {
						if (value.Length == 2) {
							var property = ctx.ResolveProperty(reader.ReadUInt16());
							return ctx.ToString(elem, property.ToXName(ctx, elem, false));
						}
						else {
							var type = ctx.ResolveType(reader.ReadUInt16());
							var name = reader.ReadString();
							var typeName = ctx.ToString(elem, type);
							return typeName + "." + name;
						}
					}

					case KnownTypes.EnumConverter: {
						uint enumVal = reader.ReadUInt32();
						// TODO: Convert to enum names
						return enumVal.ToString("D", CultureInfo.InvariantCulture);
					}

					case KnownTypes.BooleanConverter: {
						Debug.Assert(value.Length == 1);
						return (reader.ReadByte() == 1).ToString(CultureInfo.InvariantCulture);
					}

					case KnownTypes.XamlBrushSerializer: {
						switch (reader.ReadByte()) {
							case 1: // KnownSolidColor
								return string.Format(CultureInfo.InvariantCulture, "#{0:X8}", reader.ReadUInt32());
							case 2: // OtherColor
								return reader.ReadString();
						}
						break;
					}

					case KnownTypes.XamlPathDataSerializer:
						return XamlPathDeserializer.Deserialize(reader);

					case KnownTypes.XamlPoint3DCollectionSerializer:
					case KnownTypes.XamlVector3DCollectionSerializer: {
						var sb = new StringBuilder();
						var count = reader.ReadUInt32();
						for (uint i = 0; i < count; i++) {
							sb.AppendFormat(CultureInfo.InvariantCulture, "{0:R},{1:R},{2:R} ",
								reader.ReadXamlDouble(),
								reader.ReadXamlDouble(),
								reader.ReadXamlDouble());
						}
						return sb.ToString().Trim();
					}

					case KnownTypes.XamlPointCollectionSerializer: {
						var sb = new StringBuilder();
						var count = reader.ReadUInt32();
						for (uint i = 0; i < count; i++) {
							sb.AppendFormat(CultureInfo.InvariantCulture, "{0:R},{1:R} ",
								reader.ReadXamlDouble(),
								reader.ReadXamlDouble());
						}
						return sb.ToString().Trim();
					}

					case KnownTypes.XamlInt32CollectionSerializer: {
						var sb = new StringBuilder();
						var type = (IntegerCollectionType)reader.ReadByte();
						var count = reader.ReadInt32();

						switch (type) {
							case IntegerCollectionType.Consecutive: {
								var start = reader.ReadInt32();
								for (int i = 0; i < count; i++)
									sb.AppendFormat(CultureInfo.InvariantCulture, "{0:D}", start + i);
							}
								break;
							case IntegerCollectionType.U1: {
								for (int i = 0; i < count; i++)
									sb.AppendFormat(CultureInfo.InvariantCulture, "{0:D}", reader.ReadByte());
							}
								break;
							case IntegerCollectionType.U2: {
								for (int i = 0; i < count; i++)
									sb.AppendFormat(CultureInfo.InvariantCulture, "{0:D}", reader.ReadUInt16());
							}
								break;
							case IntegerCollectionType.I4: {
								for (int i = 0; i < count; i++)
									sb.AppendFormat(CultureInfo.InvariantCulture, "{0:D}", reader.ReadInt32());
							}
								break;
							default:
								throw new NotSupportedException(type.ToString());
						}
						return sb.ToString().Trim();
					}
				}
			}
			throw new NotSupportedException(ser.ToString());
		}
        /// <summary>
        /// Is known type.
        /// </summary>
        private static bool IsKnownType(Type type)
        {
            TypeSerializationInfo info = KnownTypes.GetTypeSerializationInfo(type);

            return(info != null);
        }
 protected abstract SyntaxNode RemoveAsyncTokenAndFixReturnType(IMethodSymbol methodSymbolOpt, SyntaxNode node, KnownTypes knownTypes);
Exemple #29
0
 protected override bool IsAsyncReturnType(ITypeSymbol type, KnownTypes knownTypes)
 {
     return(IsIAsyncEnumerableOrEnumerator(type, knownTypes) ||
            IsTaskLike(type, knownTypes));
 }
Exemple #30
0
 KnownMember InitMember(KnownTypes parent, string name, TypeDef type) => new KnownMember(parent, types[parent], name, type);
Exemple #31
0
 private Tuple<KnownTypes, PropertyDef, TypeDef> InitProperty(KnownTypes parent, string propertyName, TypeDef propertyType)
 {
     if (propertyName != null)
         return Tuple.Create(parent, types[parent].FindProperty(propertyName), propertyType);
     return Tuple.Create(parent, (PropertyDef)null, propertyType);
 }
Exemple #32
0
        private void AnalyzeCompilation(CompilationAnalysisContext context)
        {
            // Get the particular attributes I need to look for.
            var companyAttributeSymbol     = KnownTypes.CompanyAttribute(context.Compilation);
            var copyrightAttributeSymbol   = KnownTypes.CopyrightAttribute(context.Compilation);
            var descriptionAttributeSymbol = KnownTypes.DescriptionAttribute(context.Compilation);
            var titleAttributeSymbol       = KnownTypes.TitleAttribute(context.Compilation);

            // Assume they are all not found.
            Boolean companyAttributeGood     = false;
            Boolean copyrightAttributeGood   = false;
            Boolean descriptionAttributeGood = false;
            Boolean titleAttributeGood       = false;

            // Pound through each attribute in the assembly checking that the specific ones
            // are present and the parameters are not empty.
            foreach (var attribute in context.Compilation.Assembly.GetAttributes())
            {
                if ((companyAttributeSymbol != null) && (attribute.AttributeClass.Equals(companyAttributeSymbol)))
                {
                    companyAttributeGood = CheckAttributeParameter(attribute);
                    continue;
                }

                if ((copyrightAttributeSymbol != null) && (attribute.AttributeClass.Equals(copyrightAttributeSymbol)))
                {
                    copyrightAttributeGood = CheckAttributeParameter(attribute);
                    continue;
                }

                if ((descriptionAttributeSymbol != null) && (attribute.AttributeClass.Equals(descriptionAttributeSymbol)))
                {
                    descriptionAttributeGood = CheckAttributeParameter(attribute);
                    continue;
                }

                if ((titleAttributeSymbol != null) && (attribute.AttributeClass.Equals(titleAttributeSymbol)))
                {
                    titleAttributeGood = CheckAttributeParameter(attribute);
                    continue;
                }
            }

            // If any of the assembly wide attributes are missing or empty, trigger a warning.
            if (!companyAttributeGood)
            {
                context.ReportDiagnostic(Diagnostic.Create(companyRule, Location.None));
            }

            if (!copyrightAttributeGood)
            {
                context.ReportDiagnostic(Diagnostic.Create(copyrightRule, Location.None));
            }

            if (!descriptionAttributeGood)
            {
                context.ReportDiagnostic(Diagnostic.Create(descriptionRule, Location.None));
            }

            if (!titleAttributeGood)
            {
                context.ReportDiagnostic(Diagnostic.Create(titleRule, Location.None));
            }
        }
Exemple #33
0
        Type Roslyn_ResolveType_internal(ITypeSymbol type)
        {
            // throw new NotSupportedException(type.ToString());

            // var aaaa = roslynCompilation.GetSpecialType(type.SpecialType);
            switch (type.SpecialType)
            {
            case SpecialType.System_String:
                return(typeof(string));

            case SpecialType.System_Double:
                return(typeof(Double));

            case SpecialType.System_Decimal:
                return(typeof(Decimal));

            case SpecialType.System_Int16:
                return(typeof(Int16));

            case SpecialType.System_Int32:
                return(typeof(Int32));

            case SpecialType.System_Int64:
                return(typeof(Int64));

            case SpecialType.System_Object:
                return(typeof(Object));

            case SpecialType.System_Boolean:
                return(typeof(Boolean));

            case SpecialType.System_Char:
                return(typeof(Char));

            case SpecialType.System_Void:
                return(typeof(void));

            case SpecialType.System_Array:
                return(typeof(Array));

            case SpecialType.System_DateTime:
                return(typeof(DateTime));

            case SpecialType.System_Enum:
                return(typeof(Enum));

            case SpecialType.None:
            {
                switch (type.TypeKind)
                {
                case TypeKind.ArrayType:
                {
                    var arrayTypeSymbol = type as IArrayTypeSymbol;
                    var elementType     = Roslyn_ResolveType(arrayTypeSymbol.ElementType);
                    var result          = arrayTypeSymbol.Rank == 1
                                        ? elementType.MakeArrayType()
                                        : elementType.MakeArrayType(arrayTypeSymbol.Rank);
                    return(result);
                }

                case TypeKind.Error:
                    return(null);

                case TypeKind.TypeParameter:
                {
                    var type1 = (ITypeParameterSymbol)type;
                    var a     = _knownTypes.Where(i => i.IsGenericParameter && i.DeclaringMethod != null).ToArray();
                    var b     = a.Where(i => i.DeclaringMethod.Name == type1.DeclaringMethod.Name).ToArray();

                    MethodInfo mi;
                    // mi.GetGenericArguments()
                    return(null);
                }
                }
                //var a = type.ToDisplayString();
                //var v = roslynCompilation.GlobalNamespace.GetNamespaceMembers().ToArray(); //.GetTypeByMetadataName(a);
                //var v5 = v[5].GetTypeMembers();
                if (_roslynAllNamedTypeSymbols == null)
                {
                    _roslynAllNamedTypeSymbols = Roslyn_GetNamedTypeSymbols(null);
                }

                if (type is INamedTypeSymbol)
                {
                    var b = type as INamedTypeSymbol;
                    //if (b.ContainingType != null)
                    //    throw new NotSupportedException();
                    if (b.IsGenericType)
                    {
                        var reflectionSearch = b.ToDisplayString();
                        // var reflectionSearchMd = b.OriginalDefinition.MetadataName;
                        // var reflectionSearchXx = b.ConstructUnboundGenericType();
                        var reflectionSearch2 = b.ConstructedFrom.ToDisplayString();
                        if (reflectionSearch != reflectionSearch2)
                        {
                            reflectionSearch = reflectionSearch2;
                        }
                        reflectionSearch = reflectionSearch.Substring(0, reflectionSearch.IndexOf("<", StringComparison.Ordinal)) + "`" + b.Arity.ToString();
                        Type reflected = KnownTypes.Single(i => i.FullName == reflectionSearch);


                        Type[] typeArguments = b.TypeArguments.AsEnumerable().Select(Roslyn_ResolveType).ToArray();
                        var    reflected2    = reflected.MakeGenericType(typeArguments);
                        return(reflected2);
                    }
                    if (b.ContainingType != null)
                    {
                        var ct = Roslyn_ResolveType(b.ContainingType);
                        var kt = KnownTypes.Where(i => i.DeclaringType == ct).ToArray();
                        var reflectionSearch = b.ContainingType.ToDisplayString() + "+" + b.Name;
                        var reflected        = KnownTypes.Single(i => i.FullName == reflectionSearch);
                        return(reflected);
                    }
                    else
                    {
                        var reflectionSearch = b.ToDisplayString();
                        var reflected        = KnownTypes.Single(i => i.FullName == reflectionSearch);
                        return(reflected);
                    }
                }


                throw new NotSupportedException(type.ToString());
            }

            default:
                throw new NotSupportedException(type.ToString());
            }
        }
        private IClangType ParseTypeDef(CXCursor cursor)
        {
            var originalType   = clang.getCursorType(cursor);
            var canonType      = clang.getCanonicalType(originalType);
            var typeDeclCursor = clang.getTypeDeclaration(canonType);

            if (IsCursorInSystemHeader(typeDeclCursor))
            {
                return(null);
            }

            var name = cursor.ToString();

            if (typeDeclCursor.kind == CXCursorKind.CXCursor_NoDeclFound)
            {
                if (canonType.kind != CXTypeKind.CXType_Pointer)
                {
                    // likely simple type alias
                    if (TypeRedirects.TryGetValue(name, out var renamed))
                    {
                        name = renamed;
                    }
                    if (KnownTypes.TryGetValue(name, out var knownType))
                    {
                        if (PrimitiveTypeMap.TryGetValue(canonType.kind, out var primitiveType))
                        {
                            var existingType = Module.GetType(name);
                            if (existingType == null)
                            {
                                throw new NotImplementedException();
                            }

                            switch (knownType)
                            {
                            case KnownType.Bitmask:
                            case KnownType.Enum: {
                                existingType.ChangeUnderlyingType(primitiveType.Import(Module));
                                break;
                            }

                            default:
                                break;
                            }

                            IncrementStatistic("typedefs");
                        }
                        else
                        {
                            throw new NotImplementedException();
                        }
                    }

                    return(null);
                }

                var pointeeType = clang.getPointeeType(canonType);
                var callConv    = clang.getFunctionTypeCallingConv(pointeeType);
                if (callConv == CXCallingConv.CXCallingConv_Invalid)
                {
                    // likely a pointer type alias
                    return(null);
                }

                return(ParseDelegate(cursor, callConv));
            }

            switch (typeDeclCursor.kind)
            {
            case CXCursorKind.CXCursor_UnionDecl:
            case CXCursorKind.CXCursor_StructDecl: {
                var typeName = typeDeclCursor.ToString();
                if (name == typeName)
                {
                    return(null);
                }

                throw new NotImplementedException();
            }

            case CXCursorKind.CXCursor_EnumDecl: {
                if (TypeRedirects.TryGetValue(name, out var renamed))
                {
                    name = renamed;
                }
                if (KnownTypes.TryGetValue(name, out var knownType))
                {
                    var existingType = Module.GetType(name);
                    if (existingType != null)
                    {
                        return(null);
                    }

                    switch (knownType)
                    {
                    case KnownType.Enum: {
                        throw new NotImplementedException();
                    }

                    case KnownType.Bitmask: {
                        throw new NotImplementedException();
                    }

                    default:
                        throw new NotImplementedException();
                    }
                }

                throw new NotImplementedException();
            }
            }

            IncrementStatistic("typedefs");
            throw new NotImplementedException();
        }
Exemple #35
0
 public SysXmlCursorTestCase()
 {
     KnownTypes.Add(ItemType, true);
     KnownTypes.Add(OtherType, true);
 }