当前位置: 首页>>代码示例>>C#>>正文


C# SemanticModel.GetDeclaredSymbol方法代码示例

本文整理汇总了C#中SemanticModel.GetDeclaredSymbol方法的典型用法代码示例。如果您正苦于以下问题:C# SemanticModel.GetDeclaredSymbol方法的具体用法?C# SemanticModel.GetDeclaredSymbol怎么用?C# SemanticModel.GetDeclaredSymbol使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在SemanticModel的用法示例。


在下文中一共展示了SemanticModel.GetDeclaredSymbol方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetDeclaredSymbols

        internal static IEnumerable<ISymbol> GetDeclaredSymbols(SemanticModel semanticModel, MemberDeclarationSyntax memberDeclaration, CancellationToken cancellationToken)
        {
            if (memberDeclaration is FieldDeclarationSyntax)
            {
                return ((FieldDeclarationSyntax)memberDeclaration).Declaration.Variables.Select(
                    v => semanticModel.GetDeclaredSymbol(v, cancellationToken));
            }

            return SpecializedCollections.SingletonEnumerable(
                semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken));
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:11,代码来源:GenerateFromMembersHelpers.cs

示例2: VerifyModelForDeclarationPatternDuplicateInSameScope

        protected static void VerifyModelForDeclarationPatternDuplicateInSameScope(SemanticModel model, DeclarationPatternSyntax decl)
        {
            var symbol = model.GetDeclaredSymbol(decl);
            Assert.Equal(decl.Identifier.ValueText, symbol.Name);
            Assert.Equal(decl, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
            Assert.Equal(LocalDeclarationKind.PatternVariable, ((LocalSymbol)symbol).DeclarationKind);
            Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)decl));
            Assert.NotEqual(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single());
            Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText));

            var type = ((LocalSymbol)symbol).Type;
            if (!decl.Type.IsVar || !type.IsErrorType())
            {
                Assert.Equal(type, model.GetSymbolInfo(decl.Type).Symbol);
            }
        }
开发者ID:orthoxerox,项目名称:roslyn,代码行数:16,代码来源:PatternMatchingTestBase.cs

示例3: TryInitializeState

        protected override bool TryInitializeState(
            Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken,
            out INamedTypeSymbol classType, out INamedTypeSymbol abstractClassType)
        {
            var baseClassNode = node as TypeSyntax;
            if (baseClassNode != null && baseClassNode.Parent is BaseTypeSyntax &&
                baseClassNode.Parent.IsParentKind(SyntaxKind.BaseList) &&
                ((BaseTypeSyntax)baseClassNode.Parent).Type == baseClassNode)
            {
                if (baseClassNode.Parent.Parent.IsParentKind(SyntaxKind.ClassDeclaration))
                {
                    abstractClassType = model.GetTypeInfo(baseClassNode, cancellationToken).Type as INamedTypeSymbol;
                    cancellationToken.ThrowIfCancellationRequested();

                    if (abstractClassType.IsAbstractClass())
                    {
                        var classDecl = baseClassNode.Parent.Parent.Parent as ClassDeclarationSyntax;
                        classType = model.GetDeclaredSymbol(classDecl, cancellationToken) as INamedTypeSymbol;

                        return classType != null && abstractClassType != null;
                    }
                }
            }

            classType = null;
            abstractClassType = null;
            return false;
        }
开发者ID:RoryVL,项目名称:roslyn,代码行数:28,代码来源:CSharpImplementAbstractClassService.cs

示例4: CanRemoveTypeFromParameter

        private static bool CanRemoveTypeFromParameter(
            SyntaxNode node,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            // We reduce any the parameters that are contained inside ParameterList
            if (node != null && node.IsParentKind(SyntaxKind.ParameterList) && node.Parent.IsParentKind(SyntaxKind.ParenthesizedLambdaExpression))
            {
                var parameterSyntax = (ParameterSyntax)node;
                if (parameterSyntax.Type != null)
                {
                    var annotation = new SyntaxAnnotation();
                    var newParameterSyntax = parameterSyntax.WithType(null).WithAdditionalAnnotations(annotation);

                    var oldLambda = node.FirstAncestorOrSelf<ParenthesizedLambdaExpressionSyntax>();
                    var newLambda = oldLambda.ReplaceNode(parameterSyntax, newParameterSyntax);
                    var speculationAnalyzer = new SpeculationAnalyzer(oldLambda, newLambda, semanticModel, cancellationToken);
                    newParameterSyntax = (ParameterSyntax)speculationAnalyzer.ReplacedExpression.GetAnnotatedNodesAndTokens(annotation).First();

                    var oldSymbol = semanticModel.GetDeclaredSymbol(parameterSyntax, cancellationToken);
                    var newSymbol = speculationAnalyzer.SpeculativeSemanticModel.GetDeclaredSymbol(newParameterSyntax, cancellationToken);
                    if (oldSymbol != null &&
                        newSymbol != null &&
                        oldSymbol.Type == newSymbol.Type)
                    {
                        return !speculationAnalyzer.ReplacementChangesSemantics();
                    }
                }
            }

            return false;
        }
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:32,代码来源:CSharpMiscellaneousReducer.cs

示例5: GetFixesAsync

        internal async override Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, CancellationToken cancellationToken)
        {
            IEnumerable<CodeAction> actions = null;

            // Fix 1: Add a NonSerialized attribute to the field
            var fieldNode = GetFieldDeclarationNode(nodeToFix);
            if (fieldNode != null)
            { 
                var attr = CodeGenerationSymbolFactory.CreateAttributeData(WellKnownTypes.NonSerializedAttribute(model.Compilation));
                var newNode = CodeGenerator.AddAttributes(fieldNode, document.Project.Solution.Workspace, SpecializedCollections.SingletonEnumerable(attr)).WithAdditionalAnnotations(Formatting.Formatter.Annotation);
                var newDocument = document.WithSyntaxRoot(root.ReplaceNode(fieldNode, newNode));
                var codeAction = CodeAction.Create(FxCopFixersResources.AddNonSerializedAttribute, newDocument);
                actions = SpecializedCollections.SingletonEnumerable(codeAction);

                // Fix 2: If the type of the field is defined in source, then add the serializable attribute to the type.
                var fieldSymbol = model.GetDeclaredSymbol(nodeToFix) as IFieldSymbol;
                var type = fieldSymbol.Type;
                if (type.Locations.Any(l => l.IsInSource))
                {
                    var typeDeclNode = type.DeclaringSyntaxReferences.First().GetSyntax();
                    var serializableAttr = CodeGenerationSymbolFactory.CreateAttributeData(WellKnownTypes.SerializableAttribute(model.Compilation));
                    var newTypeDeclNode = CodeGenerator.AddAttributes(typeDeclNode, document.Project.Solution.Workspace, SpecializedCollections.SingletonEnumerable(serializableAttr)).WithAdditionalAnnotations(Formatting.Formatter.Annotation);

                    var documentContainingNode = document.Project.Solution.GetDocument(typeDeclNode.SyntaxTree);
                    var docRoot = await documentContainingNode.GetSyntaxRootAsync(cancellationToken);
                    var newDocumentContainingNode = documentContainingNode.WithSyntaxRoot(docRoot.ReplaceNode(typeDeclNode, newTypeDeclNode));
                    var typeCodeAction = CodeAction.Create(FxCopFixersResources.AddSerializableAttribute, newDocumentContainingNode.Project.Solution);

                    actions = actions.Concat(typeCodeAction);
                }
            }

            return actions;
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:34,代码来源:CA2235CodeFixProviderBase.cs

示例6: GetFixesAsync

        internal override Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, CancellationToken cancellationToken)
        {
            var actions = ImmutableArray.CreateBuilder<CodeAction>();

            // Fix 1: Add a NonSerialized attribute to the field
            var fieldNode = GetFieldDeclarationNode(nodeToFix);
            if (fieldNode != null)
            {
                var generator = SyntaxGenerator.GetGenerator(document);
                var codeAction = new MyDocumentCodeAction(FxCopFixersResources.AddNonSerializedAttribute,
                                                          async ct => await AddNonSerializedAttribute(document, model, root, fieldNode, generator).ConfigureAwait(false));
                actions.Add(codeAction);

                // Fix 2: If the type of the field is defined in source, then add the serializable attribute to the type.
                var fieldSymbol = model.GetDeclaredSymbol(nodeToFix, cancellationToken) as IFieldSymbol;
                var type = fieldSymbol.Type;
                if (type.Locations.Any(l => l.IsInSource))
                {
                    var typeCodeAction = new MySolutionCodeAction(FxCopFixersResources.AddSerializableAttribute,
                                                                  async ct => await AddSerializableAttributeToType(document, model, generator, type, cancellationToken).ConfigureAwait(false));

                    actions.Add(typeCodeAction);
                }
            }

            return Task.FromResult<IEnumerable<CodeAction>>(actions.ToImmutable());
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:27,代码来源:CA2235CodeFixProviderBase.cs

示例7: RemoveFlagsAttribute

        private static SyntaxNode RemoveFlagsAttribute(Workspace workspace, SemanticModel model, SyntaxNode enumTypeSyntax, INamedTypeSymbol flagsAttributeType, CancellationToken cancellationToken)
        {
            var enumType = model.GetDeclaredSymbol(enumTypeSyntax) as INamedTypeSymbol;
            Contract.ThrowIfNull(enumType);

            var flagsAttribute = enumType.GetAttributes().First(a => a.AttributeClass == flagsAttributeType);
            return CodeGenerator.RemoveAttribute(enumTypeSyntax, workspace, flagsAttribute, CodeGenerationOptions.Default, cancellationToken);
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:8,代码来源:EnumWithFlagsCodeFixProviderBase.cs

示例8: GetUpdatedDocumentAsync

 internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, Diagnostic diagnostic, CancellationToken cancellationToken)
 {
     var classSymbol = (INamedTypeSymbol)model.GetDeclaredSymbol(nodeToFix, cancellationToken);
     var instanceConstructors = classSymbol.InstanceConstructors.Where(t => t.DeclaredAccessibility == Accessibility.Public).Select(t => GetDeclaration(t)).Where(d => d != null).ToList();
     var generator = SyntaxGenerator.GetGenerator(document);
     var newRoot = root.ReplaceNodes(instanceConstructors, (original, rewritten) => generator.WithAccessibility(original, Accessibility.Protected));
     return Task.FromResult(document.WithSyntaxRoot(newRoot));
 }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:8,代码来源:CA1012CodeFixProvider.cs

示例9: VerifyModelForDeclarationPattern

        protected static void VerifyModelForDeclarationPattern(
            SemanticModel model,
            SingleVariableDesignationSyntax designation,
            bool isShadowed,
            params IdentifierNameSyntax[] references)
        {
            var symbol = model.GetDeclaredSymbol(designation);
            Assert.Equal(designation.Identifier.ValueText, symbol.Name);
            Assert.Equal(designation, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
            Assert.Equal(LocalDeclarationKind.PatternVariable, ((LocalSymbol)symbol).DeclarationKind);
            Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)designation));

            var other = model.LookupSymbols(designation.SpanStart, name: designation.Identifier.ValueText).Single();
            if (isShadowed)
            {
                Assert.NotEqual(symbol, other);
            }
            else
            {
                Assert.Same(symbol, other);
            }

            Assert.True(model.LookupNames(designation.SpanStart).Contains(designation.Identifier.ValueText));

            var decl = (DeclarationPatternSyntax)designation.Parent;
            Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(decl.Type));
            Assert.True(SyntaxFacts.IsInTypeOnlyContext(decl.Type));

            var local = ((SourceLocalSymbol)symbol);
            var type = local.Type;
            if (type.IsErrorType())
            {
                Assert.Null(model.GetSymbolInfo(decl.Type).Symbol);
            }
            else
            {
                Assert.Equal(type, model.GetSymbolInfo(decl.Type).Symbol);
            }

            foreach (var reference in references)
            {
                Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol);
                Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: designation.Identifier.ValueText).Single());
                Assert.True(model.LookupNames(reference.SpanStart).Contains(designation.Identifier.ValueText));
            }
        }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:46,代码来源:PatternMatchingTestBase.cs

示例10: RemoveFlagsAttribute

        private static SyntaxNode RemoveFlagsAttribute(Workspace workspace, SemanticModel model, SyntaxNode enumTypeSyntax, INamedTypeSymbol flagsAttributeType, CancellationToken cancellationToken)
        {
            var enumType = model.GetDeclaredSymbol(enumTypeSyntax, cancellationToken) as INamedTypeSymbol;
            Debug.Assert(enumType != null);

            var flagsAttribute = enumType.GetAttributes().First(a => a.AttributeClass == flagsAttributeType);
            var attributeNode = flagsAttribute.ApplicationSyntaxReference.GetSyntax(cancellationToken);
            var generator = SyntaxGenerator.GetGenerator(workspace, enumTypeSyntax.Language);

            return generator.RemoveNode(enumTypeSyntax, attributeNode);
        }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:11,代码来源:EnumWithFlagsCodeFixProviderBase.cs

示例11: ReferenceRewriter

 private ReferenceRewriter(
     SemanticModel semanticModel,
     VariableDeclaratorSyntax variableDeclarator,
     ExpressionSyntax expressionToInline,
     CancellationToken cancellationToken)
 {
     _semanticModel = semanticModel;
     _localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken);
     _variableDeclarator = variableDeclarator;
     _expressionToInline = expressionToInline;
     _cancellationToken = cancellationToken;
 }
开发者ID:Rickinio,项目名称:roslyn,代码行数:12,代码来源:InlineTemporaryCodeRefactoringProvider.ReferenceRewriter.cs

示例12: GetUpdatedDocumentAsync

        internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
        {
            var classSymbol = (INamedTypeSymbol)model.GetDeclaredSymbol(nodeToFix);
            var instanceConstructors = classSymbol.InstanceConstructors.Where(t => t.DeclaredAccessibility == Accessibility.Public).Select(t => t.DeclaringSyntaxReferences[0].GetSyntax());
            var workspace = document.Project.Solution.Workspace;
            Func<SyntaxNode, SyntaxNode, SyntaxNode> replacementForNodes = (constructorNode, dummy) =>
                {
                    var newSyntax = CodeGenerator.UpdateDeclarationAccessibility(constructorNode, workspace, Accessibility.Protected, cancellationToken: cancellationToken).WithAdditionalAnnotations(Formatter.Annotation);
                    return newSyntax;
                };

            return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNodes(instanceConstructors, replacementForNodes)));
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:13,代码来源:CA1012CodeFixProvider.cs

示例13: ConvertMethodToAsync

        protected async Task<SyntaxNode> ConvertMethodToAsync(Document document, SemanticModel semanticModel, SyntaxNode methodNode, CancellationToken cancellationToken)
        {
            var methodSymbol = semanticModel.GetDeclaredSymbol(methodNode, cancellationToken) as IMethodSymbol;

            if (methodSymbol.ReturnsVoid)
            {
                return AddAsyncKeyword(methodNode);
            }

            var returnType = methodSymbol.ReturnType;
            var compilation = semanticModel.Compilation;

            var taskSymbol = compilation.GetTypeByMetadataName(SystemThreadingTasksTask);
            var genericTaskSymbol = compilation.GetTypeByMetadataName(SystemThreadingTasksTaskT);
            if (taskSymbol == null)
            {
                return null;
            }

            if (returnType is IErrorTypeSymbol)
            {
                // The return type of the method will not bind.  This could happen for a lot of reasons.
                // The type may not actually exist or the user could just be missing a using/import statement.
                // We're going to try and see if there are any known types that have the same name as 
                // our return type, and then check if those are convertible to Task.  If they are then
                // we assume the user just has a missing using.  If they are not, we wrap the return
                // type in a generic Task.
                var typeName = returnType.Name;
                var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
                var results = await SymbolFinder.FindDeclarationsAsync(
                    document.Project, typeName, ignoreCase: syntaxFacts.IsCaseSensitive, filter: SymbolFilter.Type, cancellationToken: cancellationToken).ConfigureAwait(false);

                if (results.OfType<ITypeSymbol>().Any(s => DoesConversionExist(compilation, s, taskSymbol)))
                {
                    return AddAsyncKeyword(methodNode);
                }

                return AddAsyncKeywordAndTaskReturnType(methodNode, returnType, genericTaskSymbol);
            }

            if (DoesConversionExist(compilation, returnType, taskSymbol))
            {
                return AddAsyncKeyword(methodNode);
            }

            return AddAsyncKeywordAndTaskReturnType(methodNode, returnType, genericTaskSymbol);
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:47,代码来源:AbstractAddAsyncCodeFixProvider.cs

示例14: GetExistingNamespaces

        private IList<INamespaceSymbol> GetExistingNamespaces(
            SemanticModel semanticModel, NamespaceDeclarationSyntax namespaceDeclaration, CancellationToken cancellationToken)
        {
            var q = from u in namespaceDeclaration.Usings
                    let symbol = semanticModel.GetSymbolInfo(u.Name, cancellationToken).Symbol as INamespaceSymbol
                    where symbol != null && !symbol.IsGlobalNamespace
                    select symbol;

            var usingImports = q.ToList();

            var namespaceSymbol = semanticModel.GetDeclaredSymbol(namespaceDeclaration, cancellationToken) as INamespaceSymbol;
            var namespaceImports = GetContainingNamespacesAndThis(namespaceSymbol).ToList();

            var outerNamespaces = this.GetExistingNamespaces(semanticModel, namespaceDeclaration.Parent, cancellationToken);

            return outerNamespaces.Concat(namespaceImports).Concat(usingImports)
                                  .Distinct()
                                  .OrderBy(INamespaceSymbolExtensions.CompareNamespaces)
                                  .ToList();
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:20,代码来源:UsingDirectivesAdder.cs

示例15: GetUpdatedDocumentAsync

        internal async override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var symbol = model.GetDeclaredSymbol(nodeToFix, cancellationToken);
            var generator = SyntaxGenerator.GetGenerator(document);

            // There was no constructor and so the diagnostic was on the type. Generate a serlialization ctor.
            if (symbol.Kind == SymbolKind.NamedType)
            {
                var typeSymbol = symbol as INamedTypeSymbol;
                var throwStatement = generator.ThrowStatement(generator.ObjectCreationExpression(generator.DottedName("System.NotImplementedException")));

                var ctorDecl = generator.ConstructorDeclaration(
                    typeSymbol.Name,
                    new[]
                    {
                        generator.ParameterDeclaration("serializationInfo", generator.TypeExpression(WellKnownTypes.SerializationInfo(model.Compilation))),
                        generator.ParameterDeclaration("streamingContext", generator.TypeExpression(WellKnownTypes.StreamingContext(model.Compilation)))
                    },
                    typeSymbol.IsSealed ? Accessibility.Private : Accessibility.Protected,
                    statements: new[] { throwStatement });

                var editor = SymbolEditor.Create(document.Project.Solution);
                await editor.EditOneDeclarationAsync(typeSymbol, nodeToFix.GetLocation(), (e, d) => e.AddMember(d, ctorDecl), cancellationToken);
                return editor.GetChangedDocuments().First();
            }
            else if (symbol.Kind == SymbolKind.Method)
            {
                // There is a serialization constructor but with incorrect accessibility. Set that right.
                var methodSymbol = symbol as IMethodSymbol;

                // This would be constructor and can have only one definition.
                Debug.Assert(methodSymbol.IsConstructor() && methodSymbol.DeclaringSyntaxReferences.Count() == 1);
                var declaration = await methodSymbol.DeclaringSyntaxReferences.First().GetSyntaxAsync(cancellationToken);

                var newAccessibility = methodSymbol.ContainingType.IsSealed ? Accessibility.Private : Accessibility.Protected;
                var newDecl = generator.WithAccessibility(declaration, newAccessibility);
                return document.WithSyntaxRoot(root.ReplaceNode(declaration, newDecl));
            }

            return document;
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:41,代码来源:CA2229CodeFixProvider.cs


注:本文中的SemanticModel.GetDeclaredSymbol方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。