Пример #1
0
        private async Task <Document> AddAssemblyInfoRegionAsync(Document document, Microsoft.CodeAnalysis.ISymbol symbol, CancellationToken cancellationToken)
        {
            var assemblyInfo = OmniSharpMetadataAsSourceHelpers.GetAssemblyInfo(symbol.ContainingAssembly);
            var compilation  = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

            var assemblyPath = OmniSharpMetadataAsSourceHelpers.GetAssemblyDisplay(compilation, symbol.ContainingAssembly);

            var regionTrivia = SyntaxFactory.RegionDirectiveTrivia(true)
                               .WithTrailingTrivia(new[] { SyntaxFactory.Space, SyntaxFactory.PreprocessingMessage(assemblyInfo) });

            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var newRoot = oldRoot.WithLeadingTrivia(new[]
            {
                SyntaxFactory.Trivia(regionTrivia),
                SyntaxFactory.CarriageReturnLineFeed,
                SyntaxFactory.Comment("// " + assemblyPath),
                SyntaxFactory.CarriageReturnLineFeed,
                SyntaxFactory.Comment($"// Decompiled with ICSharpCode.Decompiler {decompilerVersion.FileVersion}"),
                SyntaxFactory.CarriageReturnLineFeed,
                SyntaxFactory.Trivia(SyntaxFactory.EndRegionDirectiveTrivia(true)),
                SyntaxFactory.CarriageReturnLineFeed,
                SyntaxFactory.CarriageReturnLineFeed
            });

            return(document.WithSyntaxRoot(newRoot));
        }
Пример #2
0
        public static ITypeSymbol InferAwaitableReturnType(this ISymbol symbol, SemanticModel semanticModel, int position)
        {
            var methodSymbol = symbol as IMethodSymbol;

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

            var returnType = methodSymbol.ReturnType;

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

            var potentialGetAwaiters = semanticModel.LookupSymbols(position, container: returnType, name: WellKnownMemberNames.GetAwaiter, includeReducedExtensionMethods: true);
            var getAwaiters          = potentialGetAwaiters.OfType <IMethodSymbol>().Where(x => !x.Parameters.Any());

            if (!getAwaiters.Any())
            {
                return(null);
            }

            var getResults = getAwaiters.SelectMany(g => semanticModel.LookupSymbols(position, container: g.ReturnType, name: WellKnownMemberNames.GetResult));

            var getResult = getResults.OfType <IMethodSymbol>().FirstOrDefault(g => !g.IsStatic);

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

            return(getResult.ReturnType);
        }
        static string GetSource(Microsoft.CodeAnalysis.ISymbol symbol)
        {
            switch (symbol.Kind)
            {
            case Microsoft.CodeAnalysis.SymbolKind.Alias:
            case Microsoft.CodeAnalysis.SymbolKind.ArrayType:
            case Microsoft.CodeAnalysis.SymbolKind.Assembly:
            case Microsoft.CodeAnalysis.SymbolKind.DynamicType:
            case Microsoft.CodeAnalysis.SymbolKind.ErrorType:
            case Microsoft.CodeAnalysis.SymbolKind.Label:
            case Microsoft.CodeAnalysis.SymbolKind.Local:
            case Microsoft.CodeAnalysis.SymbolKind.NetModule:
            case Microsoft.CodeAnalysis.SymbolKind.PointerType:
            case Microsoft.CodeAnalysis.SymbolKind.Field:
            case Microsoft.CodeAnalysis.SymbolKind.Parameter:
            case Microsoft.CodeAnalysis.SymbolKind.RangeVariable:
            case Microsoft.CodeAnalysis.SymbolKind.TypeParameter:
            case Microsoft.CodeAnalysis.SymbolKind.Preprocessing:
                return("field");

            case Microsoft.CodeAnalysis.SymbolKind.NamedType:
                var namedTypeSymbol = (Microsoft.CodeAnalysis.INamedTypeSymbol)symbol;
                switch (namedTypeSymbol.TypeKind)
                {
                case Microsoft.CodeAnalysis.TypeKind.Class:
                    return("class");

                case Microsoft.CodeAnalysis.TypeKind.Delegate:
                    return("delegate");

                case Microsoft.CodeAnalysis.TypeKind.Enum:
                    return("enum");

                case Microsoft.CodeAnalysis.TypeKind.Interface:
                    return("interface");

                case Microsoft.CodeAnalysis.TypeKind.Struct:
                    return("struct");

                default:
                    return("class");
                }

            case Microsoft.CodeAnalysis.SymbolKind.Method:
                return("method");

            case Microsoft.CodeAnalysis.SymbolKind.Namespace:
                return("name-space");

            case Microsoft.CodeAnalysis.SymbolKind.Property:
                return("property");

            case Microsoft.CodeAnalysis.SymbolKind.Event:
                return("event");

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Пример #4
0
        public static INamedTypeSymbol GetContainingTypeOrThis(this ISymbol symbol)
        {
            if (symbol is INamedTypeSymbol)
            {
                return((INamedTypeSymbol)symbol);
            }

            return(symbol.ContainingType);
        }
Пример #5
0
        public static ISymbol ConvertThisParameterToType(this ISymbol symbol)
        {
            if (symbol.IsThisParameter())
            {
                return(((IParameterSymbol)symbol).Type);
            }

            return(symbol);
        }
Пример #6
0
        //        public static ImmutableArray<ISymbol> ExplicitInterfaceImplementations(this ISymbol symbol)
        //        {
        //            return symbol.TypeSwitch(
        //                (IEventSymbol @event) => @event.ExplicitInterfaceImplementations.As<ISymbol>(),
        //                (IMethodSymbol method) => method.ExplicitInterfaceImplementations.As<ISymbol>(),
        //                (IPropertySymbol property) => property.ExplicitInterfaceImplementations.As<ISymbol>(),
        //                _ => ImmutableArray.Create<ISymbol>());
        //        }

        public static bool IsOverridable(this ISymbol symbol)
        {
            return
                (symbol != null &&
                 symbol.ContainingType != null &&
                 symbol.ContainingType.TypeKind == TypeKind.Class &&
                 (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride) &&
                 !symbol.IsSealed);
        }
Пример #7
0
        public static bool IsEventAccessor(this ISymbol symbol)
        {
            var method = symbol as IMethodSymbol;

            return(method != null &&
                   (method.MethodKind == MethodKind.EventAdd ||
                    method.MethodKind == MethodKind.EventRaise ||
                    method.MethodKind == MethodKind.EventRemove));
        }
Пример #8
0
        public static bool IsNew(this ISymbol symbol)
        {
            switch (symbol.Kind)
            {
            case SymbolKind.Event:
            {
                var @event = symbol as IEventSymbol;

                if (@event != null && (@event.ContainingType.BaseType != null && @event.ContainingType.BaseType.GetAllMembers().OfType <IEventSymbol>().Any(k => k.Name == @event.Name) && @event.IsOverride == false))
                {
                    return(true);
                }
            }
            break;

            case SymbolKind.Method:
            {
                var @method = symbol as IMethodSymbol;
                if (@method != null && (@method.ContainingType.BaseType != null && @method.ContainingType.BaseType.GetAllMembers().OfType <IMethodSymbol>().Any(k => MemberUtilities.CompareMethods(k, @method)) && @method.IsOverride == false))
                {
                    return(true);
                }
            }
            break;


            case SymbolKind.Property:
            {
                var @property = symbol as IPropertySymbol;

                if (@property != null && (@property.ContainingType.BaseType != null && @property.ContainingType.BaseType.GetAllMembers().OfType <IPropertySymbol>().Any(k => k.Name == @property.Name) && @property.IsOverride == false))
                {
                    return(true);
                }
            }

            break;


            case SymbolKind.Field:     // New Field is nothing special, base field
            {
                /*  var @field = symbol as IFieldSymbol;
                 * if (@field != null && (@field.ContainingType.BaseType != null && @field.ContainingType.BaseType.GetAllMembers().OfType<IFieldSymbol>().Any(k => k.Name == @field.Name) && @field.IsOverride == false))
                 * {
                 *    return true;
                 * }*/
                return(false);
            }
            break;
            }

            return(false);
        }
Пример #9
0
        public static int GetArity(this ISymbol symbol)
        {
            switch (symbol.Kind)
            {
            case SymbolKind.NamedType:
                return(((INamedTypeSymbol)symbol).Arity);

            case SymbolKind.Method:
                return(((IMethodSymbol)symbol).Arity);

            default:
                return(0);
            }
        }
Пример #10
0
        public static ISymbol OverriddenMember(this ISymbol symbol)
        {
            switch (symbol.Kind)
            {
            case SymbolKind.Event:
                return(((IEventSymbol)symbol).OverriddenEvent);

            case SymbolKind.Method:
                return(((IMethodSymbol)symbol).OverriddenMethod);

            case SymbolKind.Property:
                return(((IPropertySymbol)symbol).OverriddenProperty);
            }

            return(null);
        }
Пример #11
0
        public static Accessibility GetResultantVisibility(this ISymbol symbol)
        {
            // Start by assuming it's visible.
            var visibility = Accessibility.Public;

            switch (symbol.Kind)
            {
            case SymbolKind.Alias:
                // Aliases are uber private.  They're only visible in the same file that they
                // were declared in.
                return(Accessibility.Private);

            case SymbolKind.Parameter:
                // Parameters are only as visible as their containing symbol
                return(GetResultantVisibility(symbol.ContainingSymbol));

            case SymbolKind.TypeParameter:
                // Type Parameters are private.
                return(Accessibility.Private);
            }

            while (symbol != null && symbol.Kind != SymbolKind.Namespace)
            {
                switch (symbol.DeclaredAccessibility)
                {
                // If we see anything private, then the symbol is private.
                case Accessibility.NotApplicable:
                case Accessibility.Private:
                    return(Accessibility.Private);

                // If we see anything internal, then knock it down from public to
                // internal.
                case Accessibility.Internal:
                case Accessibility.ProtectedAndInternal:
                    visibility = Accessibility.Internal;
                    break;

                    // For anything else (Public, Protected, ProtectedOrInternal), the
                    // symbol stays at the level we've gotten so far.
                }

                symbol = symbol.ContainingSymbol;
            }

            return(visibility);
        }
Пример #12
0
        /// <returns>
        /// Returns true if symbol is a local variable and its declaring syntax node is
        /// after the current position, false otherwise (including for non-local symbols)
        /// </returns>
        public static bool IsInaccessibleLocal(this ISymbol symbol, int position)
        {
            if (symbol.Kind != SymbolKind.Local)
            {
                return(false);
            }

            // Implicitly declared locals (with Option Explicit Off in VB) are scoped to the entire
            // method and should always be considered accessible from within the same method.
            if (symbol.IsImplicitlyDeclared)
            {
                return(false);
            }

            var declarationSyntax = symbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).FirstOrDefault();

            return(declarationSyntax != null && position < declarationSyntax.SpanStart);
        }
Пример #13
0
        public static ITypeSymbol GetMemberType(this ISymbol symbol)
        {
            switch (symbol.Kind)
            {
            case SymbolKind.Field:
                return(((IFieldSymbol)symbol).Type);

            case SymbolKind.Property:
                return(((IPropertySymbol)symbol).Type);

            case SymbolKind.Method:
                return(((IMethodSymbol)symbol).ReturnType);

            case SymbolKind.Event:
                return(((IEventSymbol)symbol).Type);
            }

            return(null);
        }
Пример #14
0
        public static bool IsWriteableFieldOrProperty(this ISymbol symbol)
        {
            var fieldSymbol = symbol as IFieldSymbol;

            if (fieldSymbol != null)
            {
                return(!fieldSymbol.IsReadOnly &&
                       !fieldSymbol.IsConst);
            }

            var propertySymbol = symbol as IPropertySymbol;

            if (propertySymbol != null)
            {
                return(!propertySymbol.IsReadOnly);
            }

            return(false);
        }
Пример #15
0
        public static ISymbol GetOriginalUnreducedDefinition(this ISymbol symbol)
        {
            if (symbol.IsReducedExtension())
            {
                // note: ReducedFrom is only a method definition and includes no type arguments.
                symbol = ((IMethodSymbol)symbol).GetConstructedReducedFrom();
            }

            if (symbol.IsFunctionValue())
            {
                var method = symbol.ContainingSymbol as IMethodSymbol;
                if (method != null)
                {
                    symbol = method;

                    if (method.AssociatedSymbol != null)
                    {
                        symbol = method.AssociatedSymbol;
                    }
                }
            }

            if (symbol.IsNormalAnonymousType() || symbol.IsAnonymousTypeProperty())
            {
                return(symbol);
            }

            var parameter = symbol as IParameterSymbol;

            if (parameter != null)
            {
                var method = parameter.ContainingSymbol as IMethodSymbol;
                if (method.IsReducedExtension() == true)
                {
                    symbol = method.GetConstructedReducedFrom().Parameters[parameter.Ordinal + 1];
                }
            }

            return(symbol.OriginalDefinition);
        }
Пример #16
0
//        public static DeclarationModifiers GetSymbolModifiers(this ISymbol symbol)
//        {
//            return new DeclarationModifiers(
//                isStatic: symbol.IsStatic,
//                isAbstract: symbol.IsAbstract,
//                isUnsafe: symbol.IsUnsafe(),
//                isVirtual: symbol.IsVirtual,
//                isOverride: symbol.IsOverride,
//                isSealed: symbol.IsSealed);
//        }

        public static ITypeSymbol GetSymbolType(this ISymbol symbol)
        {
            var localSymbol = symbol as ILocalSymbol;

            if (localSymbol != null)
            {
                return(localSymbol.Type);
            }

            var fieldSymbol = symbol as IFieldSymbol;

            if (fieldSymbol != null)
            {
                return(fieldSymbol.Type);
            }

            var propertySymbol = symbol as IPropertySymbol;

            if (propertySymbol != null)
            {
                return(propertySymbol.Type);
            }

            var parameterSymbol = symbol as IParameterSymbol;

            if (parameterSymbol != null)
            {
                return(parameterSymbol.Type);
            }

            var aliasSymbol = symbol as IAliasSymbol;

            if (aliasSymbol != null)
            {
                return(aliasSymbol.Target as ITypeSymbol);
            }

            return(symbol as ITypeSymbol);
        }
Пример #17
0
        public static Accessibility ComputeResultantAccessibility(this ISymbol symbol, ITypeSymbol finalDestination)
        {
            if (symbol == null)
            {
                return(Accessibility.Private);
            }

            switch (symbol.DeclaredAccessibility)
            {
            default:
                return(symbol.DeclaredAccessibility);

            case Accessibility.ProtectedAndInternal:
                return(symbol.ContainingAssembly.GivesAccessTo(finalDestination.ContainingAssembly)
                        ? Accessibility.ProtectedAndInternal
                        : Accessibility.Internal);

            case Accessibility.ProtectedOrInternal:
                return(symbol.ContainingAssembly.GivesAccessTo(finalDestination.ContainingAssembly)
                        ? Accessibility.ProtectedOrInternal
                        : Accessibility.Protected);
            }
        }
Пример #18
0
        public static bool IsOrContainsAccessibleAttribute(this ISymbol symbol, ISymbol withinType, IAssemblySymbol withinAssembly)
        {
            var alias = symbol as IAliasSymbol;

            if (alias != null)
            {
                symbol = alias.Target;
            }

            var namespaceOrType = symbol as INamespaceOrTypeSymbol;

            if (namespaceOrType == null)
            {
                return(false);
            }

//            if (namespaceOrType.IsAttribute() && namespaceOrType.IsAccessibleWithin(withinType ?? withinAssembly))
//            {
//                return true;
//            }

            return(namespaceOrType.GetMembers().Any(nt => nt.IsOrContainsAccessibleAttribute(withinType, withinAssembly)));
        }
Пример #19
0
        /// <summary>
        /// If the <paramref name="symbol"/> is a method symbol, returns True if the method's return type is "awaitable".
        /// If the <paramref name="symbol"/> is a type symbol, returns True if that type is "awaitable".
        /// An "awaitable" is any type that exposes a GetAwaiter method which returns a valid "awaiter". This GetAwaiter method may be an instance method or an extension method.
        /// </summary>
        public static bool IsAwaitable(this ISymbol symbol, SemanticModel semanticModel, int position)
        {
            IMethodSymbol methodSymbol = symbol as IMethodSymbol;
            ITypeSymbol   typeSymbol   = null;

            if (methodSymbol == null)
            {
                typeSymbol = symbol as ITypeSymbol;
                if (typeSymbol == null)
                {
                    return(false);
                }
            }
            else
            {
                if (methodSymbol.ReturnType == null)
                {
                    return(false);
                }

                // dynamic
                if (methodSymbol.ReturnType.TypeKind == TypeKind.Dynamic &&
                    methodSymbol.MethodKind != MethodKind.BuiltinOperator)
                {
                    return(true);
                }
            }

            // otherwise: needs valid GetAwaiter
            var potentialGetAwaiters = semanticModel.LookupSymbols(position,
                                                                   container: typeSymbol ?? methodSymbol.ReturnType.OriginalDefinition,
                                                                   name: WellKnownMemberNames.GetAwaiter,
                                                                   includeReducedExtensionMethods: true);
            var getAwaiters = potentialGetAwaiters.OfType <IMethodSymbol>().Where(x => !x.Parameters.Any());

            return(getAwaiters.Any(VerifyGetAwaiter));
        }
Пример #20
0
        public static bool IsImplementable(this ISymbol symbol)
        {
            if (symbol != null &&
                symbol.ContainingType != null &&
                symbol.ContainingType.TypeKind == TypeKind.Interface)
            {
                if (symbol.Kind == SymbolKind.Event)
                {
                    return(true);
                }

                if (symbol.Kind == SymbolKind.Property)
                {
                    return(true);
                }

                if (symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.Ordinary)
                {
                    return(true);
                }
            }

            return(false);
        }
        internal static async Task <long> GetLinesOfCodeAsync(ImmutableArray <SyntaxReference> declarations, ISymbol symbol, SemanticModelProvider semanticModelProvider, CancellationToken cancellationToken)
        {
            long linesOfCode = 0;

            foreach (var decl in declarations)
            {
                SyntaxNode declSyntax = await GetTopmostSyntaxNodeForDeclarationAsync(decl, symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false);

                // For namespace symbols, don't count lines of code for declarations of child namespaces.
                // For example, "namespace N1.N2 { }" is a declaration reference for N1, but the actual declaration is for N2.
                if (symbol.Kind == SymbolKind.Namespace)
                {
                    var model = semanticModelProvider.GetSemanticModel(declSyntax);
                    if (model.GetDeclaredSymbol(declSyntax, cancellationToken) != (object)symbol)
                    {
                        continue;
                    }
                }

                FileLinePositionSpan linePosition = declSyntax.SyntaxTree.GetLineSpan(declSyntax.FullSpan, cancellationToken);
                long delta = linePosition.EndLinePosition.Line - linePosition.StartLinePosition.Line;
                if (delta == 0)
                {
                    // Declaration on a single line, we count it as a separate line.
                    delta = 1;
                }

                linesOfCode += delta;
            }

            return(linesOfCode);
        }
        internal static async Task <(int cyclomaticComplexity, ComputationalComplexityMetrics computationalComplexityMetrics)> ComputeCoupledTypesAndComplexityExcludingMemberDeclsAsync(
            ImmutableArray <SyntaxReference> declarations,
            ISymbol symbol,
            ImmutableHashSet <INamedTypeSymbol> .Builder builder,
            SemanticModelProvider semanticModelProvider,
            CancellationToken cancellationToken)
        {
            int cyclomaticComplexity = 0;
            ComputationalComplexityMetrics computationalComplexityMetrics = ComputationalComplexityMetrics.Default;

            var nodesToProcess           = new Queue <SyntaxNode>();
            var applicableAttributeNodes = PooledHashSet <SyntaxNode> .GetInstance();

            foreach (var declaration in declarations)
            {
                SyntaxNode syntax = await GetTopmostSyntaxNodeForDeclarationAsync(declaration, symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false);

                nodesToProcess.Enqueue(syntax);

                // Ensure we process parameter initializers and attributes.
                var parameters = GetParameters(symbol);
                foreach (var parameter in parameters)
                {
                    var parameterSyntaxRef = parameter.DeclaringSyntaxReferences.FirstOrDefault();
                    if (parameterSyntaxRef != null)
                    {
                        var parameterSyntax = await parameterSyntaxRef.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);

                        nodesToProcess.Enqueue(parameterSyntax);
                    }
                }

                var attributes = symbol.GetAttributes();
                if (symbol is IMethodSymbol methodSymbol)
                {
                    attributes = attributes.AddRange(methodSymbol.GetReturnTypeAttributes());
                }

                foreach (var attribute in attributes)
                {
                    if (attribute.ApplicationSyntaxReference != null &&
                        attribute.ApplicationSyntaxReference.SyntaxTree == declaration.SyntaxTree)
                    {
                        var attributeSyntax = await attribute.ApplicationSyntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);

                        if (applicableAttributeNodes.Add(attributeSyntax))
                        {
                            nodesToProcess.Enqueue(attributeSyntax);
                        }
                    }
                }

                do
                {
                    var node  = nodesToProcess.Dequeue();
                    var model = semanticModelProvider.GetSemanticModel(node);

                    if (!ReferenceEquals(node, syntax))
                    {
                        var declaredSymbol = model.GetDeclaredSymbol(node, cancellationToken);
                        if (declaredSymbol != null && !Equals(symbol, declaredSymbol) && declaredSymbol.Kind != SymbolKind.Parameter)
                        {
                            // Skip member declarations.
                            continue;
                        }
                    }

                    var typeInfo = model.GetTypeInfo(node, cancellationToken);
                    AddCoupledNamedTypesCore(builder, typeInfo.Type);

                    var operationBlock = model.GetOperation(node, cancellationToken);
                    if (operationBlock != null && operationBlock.Parent == null)
                    {
                        switch (operationBlock.Kind)
                        {
                        case OperationKind.Block:
                        case OperationKind.MethodBodyOperation:
                        case OperationKind.ConstructorBodyOperation:
                            cyclomaticComplexity += 1;
                            break;

                        case OperationKind.None:
                            // Skip non-applicable attributes.
                            if (!applicableAttributeNodes.Contains(node))
                            {
                                continue;
                            }

                            break;
                        }

                        computationalComplexityMetrics = computationalComplexityMetrics.Union(ComputationalComplexityMetrics.Compute(operationBlock));

                        // Add used types within executable code in the operation tree.
                        foreach (var operation in operationBlock.DescendantsAndSelf())
                        {
#if LEGACY_CODE_METRICS_MODE
                            // Legacy mode does not account for code within lambdas/local functions for code metrics.
                            if (operation.IsWithinLambdaOrLocalFunction())
                            {
                                continue;
                            }
#endif

                            if (!operation.IsImplicit && hasConditionalLogic(operation))
                            {
                                cyclomaticComplexity += 1;
                            }

                            AddCoupledNamedTypesCore(builder, operation.Type);

                            // Handle static member accesses specially as there is no operation for static type off which the member is accessed.
                            if (operation is IMemberReferenceOperation memberReference &&
                                memberReference.Member.IsStatic)
                            {
                                AddCoupledNamedTypesCore(builder, memberReference.Member.ContainingType);
                            }
                            else if (operation is IInvocationOperation invocation &&
                                     (invocation.TargetMethod.IsStatic || invocation.TargetMethod.IsExtensionMethod))
                            {
                                AddCoupledNamedTypesCore(builder, invocation.TargetMethod.ContainingType);
                            }
                        }
                    }
Пример #23
0
 public ProtocolCompletionData(ICompletionDataKeyHandler keyHandler, RoslynCodeCompletionFactory factory, int declarationBegin, ITypeSymbol currentType, Microsoft.CodeAnalysis.ISymbol member, bool afterKeyword) : base(keyHandler, factory, member, member.ToDisplayString())
 {
     this.afterKeyword     = afterKeyword;
     this.currentType      = currentType;
     this.declarationBegin = declarationBegin;
     this.GenerateBody     = true;
 }
        internal static async Task <SyntaxNode> GetTopmostSyntaxNodeForDeclarationAsync(SyntaxReference declaration, ISymbol declaredSymbol, SemanticModelProvider semanticModelProvider, CancellationToken cancellationToken)
        {
            var declSyntax = await declaration.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);

            if (declSyntax.Language == LanguageNames.VisualBasic)
            {
                SemanticModel model = semanticModelProvider.GetSemanticModel(declSyntax);
                while (declSyntax.Parent != null && Equals(model.GetDeclaredSymbol(declSyntax.Parent, cancellationToken), declaredSymbol))
                {
                    declSyntax = declSyntax.Parent;
                }
            }

            return(declSyntax);
        }
Пример #25
0
//
//		public CSharpAmbience () : base ("C#")
//		{
//		}
//
//		static Dictionary<TypeKind, string> classTypes = new Dictionary<TypeKind, string> ();
//
        public override Task <MonoDevelop.Ide.CodeCompletion.TooltipInformation> GetTooltip(CancellationToken token, Microsoft.CodeAnalysis.ISymbol entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
            return(SourceEditor.LanguageItemTooltipProvider.CreateTooltipInformation(token, null, null, entity, false, true));
        }
Пример #26
0
        public async Task <Document> AddSourceToAsync(Document document, Compilation symbolCompilation, Microsoft.CodeAnalysis.ISymbol symbol, CancellationToken cancellationToken)
        {
            // Get the name of the type the symbol is in
            var containingOrThis = symbol.GetContainingTypeOrThis();
            var fullName         = GetFullReflectionName(containingOrThis);

            var reference        = symbolCompilation.GetMetadataReference(symbol.ContainingAssembly);
            var assemblyLocation = (reference as PortableExecutableReference)?.FilePath;

            if (assemblyLocation == null)
            {
                throw new NotSupportedException("Cannot_navigate_to_the_symbol_under_the_caret");
            }

            // Decompile
            document = PerformDecompilation(document, fullName, symbolCompilation, assemblyLocation);

            document = await AddAssemblyInfoRegionAsync(document, symbol, cancellationToken).ConfigureAwait(false);

            // Convert XML doc comments to regular comments, just like MAS
            document = await ConvertDocCommentsToRegularCommentsAsync(document, cancellationToken).ConfigureAwait(false);

            var node = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            // Apply formatting rules
            document = await Formatter.FormatAsync(
                document, new[] { node.FullSpan },
                options : null, cancellationToken).ConfigureAwait(false);

            return(document);
        }
Пример #27
0
        internal static MonoDevelop.Ide.FindInFiles.SearchResult GetJumpTypePartSearchResult(Microsoft.CodeAnalysis.ISymbol part, Microsoft.CodeAnalysis.Location location)
        {
            var provider = new MonoDevelop.Ide.FindInFiles.FileProvider(location.SourceTree.FilePath);
            var doc      = TextEditorFactory.CreateNewDocument();

            doc.Text = provider.ReadString().ReadToEnd();
            int position = location.SourceSpan.Start;

            while (position + part.Name.Length < doc.Length)
            {
                if (doc.GetTextAt(position, part.Name.Length) == part.Name)
                {
                    break;
                }
                position++;
            }
            return(new MonoDevelop.Ide.FindInFiles.SearchResult(provider, position, part.Name.Length));
        }
Пример #28
0
 public AspAttributeCompletionData(Microsoft.CodeAnalysis.ISymbol member, string name = null)
     : base(name ?? member.Name, member.GetStockIcon())
 {
     this.member = member;
 }
Пример #29
0
        public static bool IsOrContainsAccessibleAttribute(this ISymbol symbol, ISymbol withinType, IAssemblySymbol withinAssembly)
        {
            var alias = symbol as IAliasSymbol;
            if (alias != null)
            {
                symbol = alias.Target;
            }

            var namespaceOrType = symbol as INamespaceOrTypeSymbol;
            if (namespaceOrType == null)
            {
                return false;
            }

//            if (namespaceOrType.IsAttribute() && namespaceOrType.IsAccessibleWithin(withinType ?? withinAssembly))
//            {
//                return true;
//            }

            return namespaceOrType.GetMembers().Any(nt => nt.IsOrContainsAccessibleAttribute(withinType, withinAssembly));
        }
Пример #30
0
        public async Task <Document> AddSourceToAsync(Document document, Compilation symbolCompilation, Microsoft.CodeAnalysis.ISymbol symbol, CancellationToken cancellationToken)
        {
            // Get the name of the type the symbol is in
            var containingOrThis = symbol.GetContainingTypeOrThis();
            var fullName         = GetFullReflectionName(containingOrThis);

            string assemblyLocation    = null;
            var    isReferenceAssembly = symbol.ContainingAssembly.GetAttributes().Any(attribute => attribute.AttributeClass.Name == nameof(ReferenceAssemblyAttribute) &&
                                                                                       attribute.AttributeClass.ToNameDisplayString() == typeof(ReferenceAssemblyAttribute).FullName);

            if (isReferenceAssembly)
            {
                try
                {
                    var fullAssemblyName = symbol.ContainingAssembly.Identity.GetDisplayName();

                    var globalAssemblyCacheType = typeof(ScriptOptions).Assembly.GetType("Microsoft.CodeAnalysis.GlobalAssemblyCache");
                    var instance = globalAssemblyCacheType.GetField("Instance", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);

                    var args = new object[] { fullAssemblyName, assemblyLocation, null, CultureInfo.CurrentCulture };
                    instance.GetType().InvokeMember("ResolvePartialName", BindingFlags.InvokeMethod, Type.DefaultBinder, instance, args);
                    assemblyLocation = (string)args[1];
                }
                catch (Exception)
                {
                    // log
                }
            }

            if (assemblyLocation == null)
            {
                var reference = symbolCompilation.GetMetadataReference(symbol.ContainingAssembly);
                assemblyLocation = (reference as PortableExecutableReference)?.FilePath;
                if (assemblyLocation == null)
                {
                    throw new NotSupportedException("Cannot_navigate_to_the_symbol_under_the_caret");
                }
            }

            // Decompile
            document = PerformDecompilation(document, fullName, symbolCompilation, assemblyLocation);

            document = await AddAssemblyInfoRegionAsync(document, symbol, cancellationToken).ConfigureAwait(false);

            // Convert XML doc comments to regular comments, just like MAS
            var docCommentFormattingService = _csharpDocumentationCommentFormattingService.CreateInstance();

            document = await ConvertDocCommentsToRegularCommentsAsync(document, docCommentFormattingService, cancellationToken).ConfigureAwait(false);

            var node = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            // Apply formatting rules
            document = await Formatter.FormatAsync(
                document, new[] { node.FullSpan },
                options : null, cancellationToken).ConfigureAwait(false);

            return(document);
        }
Пример #31
0
 public static IconId GetStockIcon(this Microsoft.CodeAnalysis.ISymbol symbol)
 {
     return("md-" + GetAccess(symbol.DeclaredAccessibility) + GetGlobal(symbol) + GetSource(symbol));
 }
		public AspAttributeCompletionData (Microsoft.CodeAnalysis.ISymbol member, string name = null)
			: base (name ?? member.Name, member.GetStockIcon ())
		{
			this.member = member;
		}