Esempio n. 1
0
 public CompilationSourceFile(ModuleContext module, SourceFile sourceFile)
 {
     this.Compiler  = module.Compiler;
     this.file      = sourceFile;
     RootPackage    = new PackageContainer(this, module);
     rootUsingScope = RootPackage;
 }
Esempio n. 2
0
            public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
            {
                if (ignoreUsingScope)
                {
                    base.VisitNamespaceDeclaration(namespaceDeclaration);
                    return;
                }
                var previousContext = context.Peek();
                var usingScope      = previousContext.CurrentUsingScope.UnresolvedUsingScope;

                foreach (string ident in namespaceDeclaration.Identifiers)
                {
                    usingScope = new UsingScope(usingScope, ident);
                }
                var currentContext = new CSharpTypeResolveContext(previousContext.CurrentModule, usingScope.Resolve(previousContext.Compilation));

                context.Push(currentContext);
                try
                {
                    astBuilder = CreateAstBuilder(currentContext);
                    base.VisitNamespaceDeclaration(namespaceDeclaration);
                }
                finally
                {
                    astBuilder = CreateAstBuilder(previousContext);
                    context.Pop();
                }
            }
        public IVariable BeginUsing()
        {
            var scope = new UsingScope(this);

            PushScope(scope);
            return(scope.UsingTarget);
        }
Esempio n. 4
0
            public FullyQualifyAmbiguousTypeNamesVisitor(TransformContext context, UsingScope usingScope)
            {
                this.ignoreUsingScope = !context.Settings.UsingDeclarations;
                this.settings         = context.Settings;

                CSharpTypeResolveContext currentContext;

                if (ignoreUsingScope)
                {
                    currentContext = new CSharpTypeResolveContext(context.TypeSystem.MainModule);
                }
                else
                {
                    this.context = new Stack <CSharpTypeResolveContext>();
                    if (!string.IsNullOrEmpty(context.CurrentTypeDefinition?.Namespace))
                    {
                        foreach (string ns in context.CurrentTypeDefinition.Namespace.Split('.'))
                        {
                            usingScope = new UsingScope(usingScope, ns);
                        }
                    }
                    currentContext = new CSharpTypeResolveContext(context.TypeSystem.MainModule, usingScope.Resolve(context.TypeSystem), context.CurrentTypeDefinition);
                    this.context.Push(currentContext);
                }
                this.astBuilder = CreateAstBuilder(currentContext);
            }
        TypeSystemAstBuilder CreateBuilder(ITypeDefinition currentTypeDef = null)
        {
            UsingScope usingScope = currentTypeDef != null?parsedFile.GetUsingScope(currentTypeDef.Region.Begin) : parsedFile.RootUsingScope;

            return(new TypeSystemAstBuilder(new CSharpResolver(
                                                new CSharpTypeResolveContext(compilation.MainAssembly, usingScope.Resolve(compilation), currentTypeDef))));
        }
Esempio n. 6
0
 public void Run(AstNode rootNode, TransformContext context)
 {
     this.context    = context;
     this.usingScope = this.rootUsingScope = rootNode.Annotation <UsingScope>();
     currentMember   = context.DecompiledMember;
     SetContext();
     rootNode.AcceptVisitor(this);
 }
            public FullyQualifyAmbiguousTypeNamesVisitor(TransformContext context, UsingScope usingScope)
            {
                this.context = new Stack <CSharpTypeResolveContext>();
                var currentContext = new CSharpTypeResolveContext(context.TypeSystem.MainAssembly, usingScope.Resolve(context.TypeSystem.Compilation));

                this.context.Push(currentContext);
                this.astBuilder = CreateAstBuilder(currentContext);
            }
Esempio n. 8
0
		public CSharpConstantValue(ConstantExpression expression, UsingScope parentUsingScope, ITypeDefinition parentTypeDefinition)
		{
			if (expression == null)
				throw new ArgumentNullException("expression");
			this.expression = expression;
			this.parentUsingScope = parentUsingScope;
			this.parentTypeDefinition = parentTypeDefinition;
		}
 void SetContext()
 {
     this.usingScope = rootUsingScope;
     foreach (var name in currentMember.Namespace.Split('.'))
     {
         usingScope = new UsingScope(usingScope, name);
     }
     resolveContext = new CSharpTypeResolveContext(currentMember.ParentAssembly, usingScope.Resolve(context.TypeSystem.Compilation), currentMember.DeclaringTypeDefinition, currentMember);
     resolver       = new CSharpResolver(resolveContext);
 }
Esempio n. 10
0
 public CSharpConstantValue(ConstantExpression expression, UsingScope parentUsingScope, ITypeDefinition parentTypeDefinition)
 {
     if (expression == null)
     {
         throw new ArgumentNullException("expression");
     }
     this.expression           = expression;
     this.parentUsingScope     = parentUsingScope;
     this.parentTypeDefinition = parentTypeDefinition;
 }
 /// <summary>
 /// Creates a new TypeSystemConvertVisitor and initializes it with a given context.
 /// </summary>
 /// <param name="parsedFile">The parsed file to which members should be added.</param>
 /// <param name="currentUsingScope">The current using scope.</param>
 /// <param name="currentTypeDefinition">The current type definition.</param>
 public TypeSystemConvertVisitor(ParsedFile parsedFile, UsingScope currentUsingScope = null, DefaultTypeDefinition currentTypeDefinition = null)
 {
     if (parsedFile == null)
     {
         throw new ArgumentNullException("parsedFile");
     }
     this.parsedFile            = parsedFile;
     this.usingScope            = currentUsingScope ?? parsedFile.RootUsingScope;
     this.currentTypeDefinition = currentTypeDefinition;
 }
        public void AddUsings(UsingScope usingScope, ICompilation compilation)
        {
            foreach (KeyValuePair <string, TypeOrNamespaceReference> alias in usingScope.UsingAliases)
            {
                AddCodeImport(alias.Value.ToString());
            }

            foreach (TypeOrNamespaceReference typeOrNamespace in usingScope.Usings)
            {
                AddCodeImport(typeOrNamespace.ToString());
            }
        }
 /// <summary>
 /// Creates a new TypeSystemConvertVisitor.
 /// </summary>
 /// <param name="pc">The parent project content (used as owner for the types being created).</param>
 /// <param name="fileName">The file name (used for DomRegions).</param>
 public TypeSystemConvertVisitor(IProjectContent pc, string fileName)
 {
     if (pc == null)
     {
         throw new ArgumentNullException("pc");
     }
     if (fileName == null)
     {
         throw new ArgumentNullException("fileName");
     }
     this.parsedFile = new ParsedFile(fileName, new UsingScope(pc));
     this.usingScope = parsedFile.RootUsingScope;
 }
Esempio n. 14
0
 public ParsedFile(string fileName, UsingScope rootUsingScope)
 {
     if (fileName == null)
     {
         throw new ArgumentNullException("fileName");
     }
     if (rootUsingScope == null)
     {
         throw new ArgumentNullException("rootUsingScope");
     }
     this.fileName       = fileName;
     this.rootUsingScope = rootUsingScope;
 }
Esempio n. 15
0
        public void Run(AstNode rootNode, TransformContext context)
        {
            // First determine all the namespaces that need to be imported:
            var requiredImports = new FindRequiredImports(context);

            rootNode.AcceptVisitor(requiredImports);

            var usingScope = new UsingScope();

            rootNode.AddAnnotation(usingScope);

            if (context.Settings.UsingDeclarations)
            {
                var insertionPoint = rootNode.Children.LastOrDefault(n => n is PreProcessorDirective p && p.Type == PreProcessorDirectiveType.Define);

                // Now add using declarations for those namespaces:
                foreach (string ns in requiredImports.ImportedNamespaces.OrderByDescending(n => n))
                {
                    Debug.Assert(context.RequiredNamespacesSuperset.Contains(ns), $"Should not insert using declaration for namespace that is missing from the superset: {ns}");
                    // we go backwards (OrderByDescending) through the list of namespaces because we insert them backwards
                    // (always inserting at the start of the list)
                    string[] parts  = ns.Split('.');
                    AstType  nsType = new SimpleType(parts[0]);
                    for (int i = 1; i < parts.Length; i++)
                    {
                        nsType = new MemberType {
                            Target = nsType, MemberName = parts[i]
                        };
                    }
                    if (context.Settings.FullyQualifyAmbiguousTypeNames)
                    {
                        var reference = nsType.ToTypeReference(NameLookupMode.TypeInUsingDeclaration) as TypeOrNamespaceReference;
                        if (reference != null)
                        {
                            usingScope.Usings.Add(reference);
                        }
                    }
                    rootNode.InsertChildAfter(insertionPoint, new UsingDeclaration {
                        Import = nsType
                    }, SyntaxTree.MemberRole);
                }
            }

            if (!context.Settings.FullyQualifyAmbiguousTypeNames)
            {
                return;
            }

            // verify that the SimpleTypes refer to the correct type (no ambiguities)
            rootNode.AcceptVisitor(new FullyQualifyAmbiguousTypeNamesVisitor(context, usingScope));
        }
        public override IEntity VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, object data)
        {
            DomRegion  region             = MakeRegion(namespaceDeclaration);
            UsingScope previousUsingScope = usingScope;

            foreach (Identifier ident in namespaceDeclaration.Identifiers)
            {
                usingScope        = new UsingScope(usingScope, NamespaceDeclaration.BuildQualifiedName(usingScope.NamespaceName, ident.Name));
                usingScope.Region = region;
            }
            base.VisitNamespaceDeclaration(namespaceDeclaration, data);
            parsedFile.UsingScopes.Add(usingScope);             // add after visiting children so that nested scopes come first
            usingScope = previousUsingScope;
            return(null);
        }
Esempio n. 17
0
            public FullyQualifyAmbiguousTypeNamesVisitor(TransformContext context, UsingScope usingScope)
            {
                this.context = new Stack <CSharpTypeResolveContext>();
                if (!string.IsNullOrEmpty(context.DecompiledTypeDefinition?.Namespace))
                {
                    foreach (string ns in context.DecompiledTypeDefinition.Namespace.Split('.'))
                    {
                        usingScope = new UsingScope(usingScope, ns);
                    }
                }
                var currentContext = new CSharpTypeResolveContext(context.TypeSystem.MainAssembly, usingScope.Resolve(context.TypeSystem.Compilation), context.DecompiledTypeDefinition);

                this.context.Push(currentContext);
                this.astBuilder = CreateAstBuilder(currentContext);
            }
Esempio n. 18
0
        void InitializeContext(UsingScope usingScope)
        {
            this.resolveContextStack = new Stack <CSharpTypeResolveContext>();
            if (!string.IsNullOrEmpty(context.DecompiledTypeDefinition?.Namespace))
            {
                foreach (string ns in context.DecompiledTypeDefinition.Namespace.Split('.'))
                {
                    usingScope = new UsingScope(usingScope, ns);
                }
            }
            var currentContext = new CSharpTypeResolveContext(context.TypeSystem.MainModule, usingScope.Resolve(context.TypeSystem), context.DecompiledTypeDefinition);

            this.resolveContextStack.Push(currentContext);
            this.resolver = new CSharpResolver(currentContext);
        }
		public ResolvedUsingScope(CSharpTypeResolveContext context, UsingScope usingScope)
		{
			if (context == null)
				throw new ArgumentNullException("context");
			if (usingScope == null)
				throw new ArgumentNullException("usingScope");
			this.parentContext = context;
			this.usingScope = usingScope;
			if (usingScope.Parent != null) {
				if (context.CurrentUsingScope == null)
					throw new InvalidOperationException();
			} else {
				if (context.CurrentUsingScope != null)
					throw new InvalidOperationException();
			}
		}
Esempio n. 20
0
        AstType ConvertNamespace(string ns)
        {
            if (resolver != null)
            {
                // Look if there's an alias to the target namespace
                for (UsingScope usingScope = resolver.CurrentUsingScope; usingScope != null; usingScope = usingScope.Parent)
                {
                    foreach (var pair in usingScope.UsingAliases)
                    {
                        // maybe add some caching? we're resolving all aliases N times when converting a namespace name with N parts
                        NamespaceResolveResult nrr = pair.Value.ResolveNamespace(resolver.Context);
                        if (nrr != null && nrr.NamespaceName == ns)
                        {
                            return(new SimpleType(pair.Key));
                        }
                    }
                }
            }

            int pos = ns.LastIndexOf('.');

            if (pos < 0)
            {
                if (IsValidNamespace(ns))
                {
                    return(new SimpleType(ns));
                }
                else
                {
                    return(new MemberType {
                        Target = new SimpleType("global"),
                        IsDoubleColon = true,
                        MemberName = ns
                    });
                }
            }
            else
            {
                string parentNamespace = ns.Substring(0, pos);
                string localNamespace  = ns.Substring(pos + 1);
                return(new MemberType {
                    Target = ConvertNamespace(parentNamespace),
                    MemberName = localNamespace
                });
            }
        }
Esempio n. 21
0
		ResolvedUsingScope MakeUsingScope(string namespaceName = "", string[] usings = null, KeyValuePair<string, string>[] usingAliases = null)
		{
			UsingScope usingScope = new UsingScope();
			if (!string.IsNullOrEmpty(namespaceName)) {
				foreach (string element in namespaceName.Split('.')) {
					usingScope = new UsingScope(usingScope, string.IsNullOrEmpty(usingScope.NamespaceName) ? element : usingScope.NamespaceName + "." + element);
				}
			}
			if (usings != null) {
				foreach (string u in usings)
					usingScope.Usings.Add(MakeReference(u));
			}
			if (usingAliases != null) {
				foreach (var pair in usingAliases)
					usingScope.UsingAliases.Add(new KeyValuePair<string, TypeOrNamespaceReference>(pair.Key, MakeReference(pair.Value)));
			}
			return usingScope.Resolve(compilation);
		}
Esempio n. 22
0
        void SetContext()
        {
            this.usingScope = rootUsingScope;
            string ns = currentMember?.Namespace ?? context.DecompiledTypeDefinition?.Namespace;

            if (ns != null)
            {
                foreach (var name in ns.Split('.'))
                {
                    usingScope = new UsingScope(usingScope, name);
                }
            }
            resolveContext = new CSharpTypeResolveContext(
                context.DecompiledAssembly,
                usingScope.Resolve(context.TypeSystem.Compilation),
                currentMember?.DeclaringTypeDefinition ?? context.DecompiledTypeDefinition,
                currentMember);
            resolver = new CSharpResolver(resolveContext);
        }
Esempio n. 23
0
        public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
        {
            var previousContext = resolveContextStack.Peek();
            var usingScope      = previousContext.CurrentUsingScope.UnresolvedUsingScope;

            foreach (string ident in namespaceDeclaration.Identifiers)
            {
                usingScope = new UsingScope(usingScope, ident);
            }
            var currentContext = new CSharpTypeResolveContext(previousContext.CurrentModule, usingScope.Resolve(previousContext.Compilation));

            resolveContextStack.Push(currentContext);
            try {
                this.resolver = new CSharpResolver(currentContext);
                base.VisitNamespaceDeclaration(namespaceDeclaration);
            } finally {
                this.resolver = new CSharpResolver(previousContext);
                resolveContextStack.Pop();
            }
        }
        /// <remarks>Does not support type arguments!</remarks>
        public static void AddSimpleUsing(this UsingScope scope, string fullName)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }
            string[] parts = fullName.Trim().Split('.');
            TypeOrNamespaceReference reference = null;

            foreach (var part in parts)
            {
                if (reference != null)
                {
                    reference = new MemberTypeOrNamespaceReference(reference, part, EmptyList <ITypeReference> .Instance);
                }
                else
                {
                    reference = new SimpleTypeOrNamespaceReference(part, EmptyList <ITypeReference> .Instance);
                }
            }

            scope.Usings.AddIfNotNull(reference);
        }
        internal static ITypeReference ConvertType(AstType type, ITypeDefinition parentTypeDefinition, IMethod parentMethodDefinition, UsingScope parentUsingScope, bool isInUsingDeclaration)
        {
            SimpleType s = type as SimpleType;

            if (s != null)
            {
                List <ITypeReference> typeArguments = new List <ITypeReference>();
                foreach (var ta in s.TypeArguments)
                {
                    typeArguments.Add(ConvertType(ta, parentTypeDefinition, parentMethodDefinition, parentUsingScope, isInUsingDeclaration));
                }
                if (typeArguments.Count == 0 && parentMethodDefinition != null)
                {
                    // SimpleTypeOrNamespaceReference doesn't support method type parameters,
                    // so we directly handle them here.
                    foreach (ITypeParameter tp in parentMethodDefinition.TypeParameters)
                    {
                        if (tp.Name == s.Identifier)
                        {
                            return(tp);
                        }
                    }
                }
                return(new SimpleTypeOrNamespaceReference(s.Identifier, typeArguments, parentTypeDefinition, parentUsingScope, isInUsingDeclaration));
            }

            PrimitiveType p = type as PrimitiveType;

            if (p != null)
            {
                switch (p.Keyword)
                {
                case "string":
                    return(KnownTypeReference.String);

                case "int":
                    return(KnownTypeReference.Int32);

                case "uint":
                    return(KnownTypeReference.UInt32);

                case "object":
                    return(KnownTypeReference.Object);

                case "bool":
                    return(KnownTypeReference.Boolean);

                case "sbyte":
                    return(KnownTypeReference.SByte);

                case "byte":
                    return(KnownTypeReference.Byte);

                case "short":
                    return(KnownTypeReference.Int16);

                case "ushort":
                    return(KnownTypeReference.UInt16);

                case "long":
                    return(KnownTypeReference.Int64);

                case "ulong":
                    return(KnownTypeReference.UInt64);

                case "float":
                    return(KnownTypeReference.Single);

                case "double":
                    return(KnownTypeReference.Double);

                case "decimal":
                    return(ReflectionHelper.ToTypeReference(TypeCode.Decimal));

                case "char":
                    return(KnownTypeReference.Char);

                case "void":
                    return(KnownTypeReference.Void);

                default:
                    return(SharedTypes.UnknownType);
                }
            }
            MemberType m = type as MemberType;

            if (m != null)
            {
                ITypeOrNamespaceReference t;
                if (m.IsDoubleColon)
                {
                    SimpleType st = m.Target as SimpleType;
                    if (st != null)
                    {
                        t = new AliasNamespaceReference(st.Identifier, parentUsingScope);
                    }
                    else
                    {
                        t = null;
                    }
                }
                else
                {
                    t = ConvertType(m.Target, parentTypeDefinition, parentMethodDefinition, parentUsingScope, isInUsingDeclaration) as ITypeOrNamespaceReference;
                }
                if (t == null)
                {
                    return(SharedTypes.UnknownType);
                }
                List <ITypeReference> typeArguments = new List <ITypeReference>();
                foreach (var ta in m.TypeArguments)
                {
                    typeArguments.Add(ConvertType(ta, parentTypeDefinition, parentMethodDefinition, parentUsingScope, isInUsingDeclaration));
                }
                return(new MemberTypeOrNamespaceReference(t, m.MemberName, typeArguments, parentTypeDefinition, parentUsingScope));
            }
            ComposedType c = type as ComposedType;

            if (c != null)
            {
                ITypeReference t = ConvertType(c.BaseType, parentTypeDefinition, parentMethodDefinition, parentUsingScope, isInUsingDeclaration);
                if (c.HasNullableSpecifier)
                {
                    t = NullableType.Create(t);
                }
                for (int i = 0; i < c.PointerRank; i++)
                {
                    t = PointerTypeReference.Create(t);
                }
                foreach (var a in c.ArraySpecifiers.Reverse())
                {
                    t = ArrayTypeReference.Create(t, a.Dimensions);
                }
                return(t);
            }
            Debug.WriteLine("Unknown node used as type: " + type);
            return(SharedTypes.UnknownType);
        }
Esempio n. 26
0
		public void AliasToImportedType2()
		{
			UsingScope mainUsingScope = new UsingScope();
			mainUsingScope.Usings.Add(MakeReference("System"));
			UsingScope nestedUsingScope = new UsingScope(mainUsingScope, "SomeNamespace");
			nestedUsingScope.UsingAliases.Add(new KeyValuePair<string, TypeOrNamespaceReference>("x", MakeReference("String")));
			var resolverWithUsing = resolver.WithCurrentUsingScope(nestedUsingScope.Resolve(compilation));
			
			TypeResolveResult trr = (TypeResolveResult)resolverWithUsing.ResolveSimpleName("x", new IType[0]);
			Assert.AreEqual("System.String", trr.Type.FullName);
		}
Esempio n. 27
0
        AstType ConvertTypeDefinition(ITypeDefinition typeDef, IList <IType> typeArguments)
        {
            Debug.Assert(typeArguments.Count >= typeDef.TypeParameterCount);
            switch (ReflectionHelper.GetTypeCode(typeDef))
            {
            case TypeCode.Object:
                return(new PrimitiveType("object"));

            case TypeCode.Boolean:
                return(new PrimitiveType("bool"));

            case TypeCode.Char:
                return(new PrimitiveType("char"));

            case TypeCode.SByte:
                return(new PrimitiveType("sbyte"));

            case TypeCode.Byte:
                return(new PrimitiveType("byte"));

            case TypeCode.Int16:
                return(new PrimitiveType("short"));

            case TypeCode.UInt16:
                return(new PrimitiveType("ushort"));

            case TypeCode.Int32:
                return(new PrimitiveType("int"));

            case TypeCode.UInt32:
                return(new PrimitiveType("uint"));

            case TypeCode.Int64:
                return(new PrimitiveType("long"));

            case TypeCode.UInt64:
                return(new PrimitiveType("ulong"));

            case TypeCode.Single:
                return(new PrimitiveType("float"));

            case TypeCode.Double:
                return(new PrimitiveType("double"));

            case TypeCode.Decimal:
                return(new PrimitiveType("decimal"));

            case TypeCode.String:
                return(new PrimitiveType("string"));
            }
            // There is no type code for System.Void
            if (typeDef.Kind == TypeKind.Void)
            {
                return(new PrimitiveType("void"));
            }

            // The number of type parameters belonging to outer classes
            int outerTypeParameterCount;

            if (typeDef.DeclaringType != null)
            {
                outerTypeParameterCount = typeDef.DeclaringType.TypeParameterCount;
            }
            else
            {
                outerTypeParameterCount = 0;
            }

            if (resolver != null)
            {
                // Look if there's an alias to the target type
                for (UsingScope usingScope = resolver.UsingScope; usingScope != null; usingScope = usingScope.Parent)
                {
                    foreach (var pair in usingScope.UsingAliases)
                    {
                        IType type = pair.Value.Resolve(resolver.Context);
                        if (TypeMatches(type, typeDef, typeArguments))
                        {
                            return(new SimpleType(pair.Key));
                        }
                    }
                }

                IList <IType> localTypeArguments;
                if (typeDef.TypeParameterCount > outerTypeParameterCount)
                {
                    localTypeArguments = new IType[typeDef.TypeParameterCount - outerTypeParameterCount];
                    for (int i = 0; i < localTypeArguments.Count; i++)
                    {
                        localTypeArguments[i] = typeArguments[outerTypeParameterCount + i];
                    }
                }
                else
                {
                    localTypeArguments = EmptyList <IType> .Instance;
                }
                TypeResolveResult trr = resolver.ResolveSimpleName(typeDef.Name, localTypeArguments) as TypeResolveResult;
                if (trr != null && !trr.IsError && TypeMatches(trr.Type, typeDef, typeArguments))
                {
                    // We can use the short type name
                    SimpleType shortResult = new SimpleType(typeDef.Name);
                    AddTypeArguments(shortResult, typeArguments, outerTypeParameterCount, typeDef.TypeParameterCount);
                    return(shortResult);
                }
            }

            MemberType result = new MemberType();

            if (typeDef.DeclaringTypeDefinition != null)
            {
                // Handle nested types
                result.Target = ConvertTypeDefinition(typeDef.DeclaringTypeDefinition, typeArguments);
            }
            else
            {
                // Handle top-level types
                if (string.IsNullOrEmpty(typeDef.Namespace))
                {
                    result.Target        = new SimpleType("global");
                    result.IsDoubleColon = true;
                }
                else
                {
                    result.Target = ConvertNamespace(typeDef.Namespace);
                }
            }
            result.MemberName = typeDef.Name;
            AddTypeArguments(result, typeArguments, outerTypeParameterCount, typeDef.TypeParameterCount);
            return(result);
        }
Esempio n. 28
0
 public void Run(AstNode rootNode, TransformContext context)
 {
     this.context    = context;
     this.usingScope = this.rootUsingScope = rootNode.Annotation <UsingScope>();
     rootNode.AcceptVisitor(this);
 }
Esempio n. 29
0
        AstType ConvertTypeHelper(ITypeDefinition typeDef, IList <IType> typeArguments)
        {
            Debug.Assert(typeArguments.Count >= typeDef.TypeParameterCount);
            TypeCode typeCode = ReflectionHelper.GetTypeCode(typeDef);

            if (typeCode != TypeCode.Empty)
            {
                string keyword = ReflectionHelper.GetCSharpNameByTypeCode(typeCode);
                if (keyword != null)
                {
                    return(new PrimitiveType(keyword));
                }
            }
            // There is no type code for System.Void
            if (typeDef.Kind == TypeKind.Void)
            {
                return(new PrimitiveType("void"));
            }

            // The number of type parameters belonging to outer classes
            int outerTypeParameterCount;

            if (typeDef.DeclaringType != null)
            {
                outerTypeParameterCount = typeDef.DeclaringType.TypeParameterCount;
            }
            else
            {
                outerTypeParameterCount = 0;
            }

            if (resolver != null)
            {
                // Look if there's an alias to the target type
                for (UsingScope usingScope = resolver.CurrentUsingScope; usingScope != null; usingScope = usingScope.Parent)
                {
                    foreach (var pair in usingScope.UsingAliases)
                    {
                        IType type = pair.Value.Resolve(resolver.Context);
                        if (TypeMatches(type, typeDef, typeArguments))
                        {
                            return(new SimpleType(pair.Key));
                        }
                    }
                }

                IList <IType> localTypeArguments;
                if (typeDef.TypeParameterCount > outerTypeParameterCount)
                {
                    localTypeArguments = new IType[typeDef.TypeParameterCount - outerTypeParameterCount];
                    for (int i = 0; i < localTypeArguments.Count; i++)
                    {
                        localTypeArguments[i] = typeArguments[outerTypeParameterCount + i];
                    }
                }
                else
                {
                    localTypeArguments = EmptyList <IType> .Instance;
                }
                TypeResolveResult trr = resolver.ResolveSimpleName(typeDef.Name, localTypeArguments) as TypeResolveResult;
                if (trr != null && !trr.IsError && TypeMatches(trr.Type, typeDef, typeArguments))
                {
                    // We can use the short type name
                    SimpleType shortResult = new SimpleType(typeDef.Name);
                    AddTypeArguments(shortResult, typeArguments, outerTypeParameterCount, typeDef.TypeParameterCount);
                    return(shortResult);
                }
            }

            MemberType result = new MemberType();

            if (typeDef.DeclaringTypeDefinition != null)
            {
                // Handle nested types
                result.Target = ConvertTypeHelper(typeDef.DeclaringTypeDefinition, typeArguments);
            }
            else
            {
                // Handle top-level types
                if (string.IsNullOrEmpty(typeDef.Namespace))
                {
                    result.Target        = new SimpleType("global");
                    result.IsDoubleColon = true;
                }
                else
                {
                    result.Target = ConvertNamespace(typeDef.Namespace);
                }
            }
            result.MemberName = typeDef.Name;
            AddTypeArguments(result, typeArguments, outerTypeParameterCount, typeDef.TypeParameterCount);
            return(result);
        }