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


C# SyntaxGenerator类代码示例

本文整理汇总了C#中SyntaxGenerator的典型用法代码示例。如果您正苦于以下问题:C# SyntaxGenerator类的具体用法?C# SyntaxGenerator怎么用?C# SyntaxGenerator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: AddFix

 private void AddFix(string codeFixTitle, CodeFixContext context, SyntaxNode root, SyntaxNode classDecl, SyntaxGenerator generator, params string[] languages)
 {
     var fix = new MyCodeAction(
         codeFixTitle,
         c => GetFix(context.Document, root, classDecl, generator, languages));
     context.RegisterCodeFix(fix, context.Diagnostics);
 }
开发者ID:GloryChou,项目名称:roslyn,代码行数:7,代码来源:ApplyDiagnosticAnalyzerAttributeFix.cs

示例2: CreateOrdinalMemberAccess

 internal SyntaxNode CreateOrdinalMemberAccess(SyntaxGenerator generator, SemanticModel model)
 {
     INamedTypeSymbol stringComparisonType = WellKnownTypes.StringComparison(model.Compilation);
     return generator.MemberAccessExpression(
         generator.TypeExpression(stringComparisonType),
         generator.IdentifierName(UseOrdinalStringComparisonAnalyzer.OrdinalText));
 }
开发者ID:bkoelman,项目名称:roslyn-analyzers,代码行数:7,代码来源:UseOrdinalStringComparison.Fixer.cs

示例3: GetInvertedStatement

 private SyntaxNode GetInvertedStatement(
     SyntaxGenerator generator, IMethodSymbol containingOperator, Compilation compilation)
 {
     if (containingOperator.Name == WellKnownMemberNames.EqualityOperatorName)
     {
         return generator.ReturnStatement(
             generator.LogicalNotExpression(
                 generator.ValueEqualsExpression(
                     generator.IdentifierName(containingOperator.Parameters[0].Name),
                     generator.IdentifierName(containingOperator.Parameters[1].Name))));
     }
     else if (containingOperator.Name == WellKnownMemberNames.InequalityOperatorName)
     {
         return generator.ReturnStatement(
             generator.LogicalNotExpression(
                 generator.ValueNotEqualsExpression(
                     generator.IdentifierName(containingOperator.Parameters[0].Name),
                     generator.IdentifierName(containingOperator.Parameters[1].Name))));
     }
     else
     {
         // If it's a  <   >   <=   or  >=   operator then we can't simply invert a call
         // to the existing operator.  i.e. the body of the "<" method should *not* be:
         //    return !(a > b);
         // Just provide a throwing impl for now.
         return generator.DefaultMethodStatement(compilation);
     }
 }
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:28,代码来源:OperatorsShouldHaveSymmetricalOverloads.Fixer.cs

示例4: CreateOrdinalMemberAccess

 internal SyntaxNode CreateOrdinalMemberAccess(SyntaxGenerator syntaxFactoryService, SemanticModel model)
 {
     var stringComparisonType = WellKnownTypes.StringComparison(model.Compilation);
     return syntaxFactoryService.MemberAccessExpression(
         syntaxFactoryService.TypeExpression(stringComparisonType),
         syntaxFactoryService.IdentifierName(UseOrdinalStringComparisonAnalyzer.OrdinalText));
 }
开发者ID:maggiemsft,项目名称:roslyn-analyzers,代码行数:7,代码来源:UseOrdinalStringComparison.Fixer.cs

示例5: AddNonSerializedAttribute

 private Task<Document> AddNonSerializedAttribute(Document document, SemanticModel model, SyntaxNode root, SyntaxNode fieldNode, SyntaxGenerator generator)
 {
     var attr = generator.Attribute(generator.TypeExpression(WellKnownTypes.NonSerializedAttribute(model.Compilation)));
     var newNode = generator.AddAttributes(fieldNode, attr);
     var newDocument = document.WithSyntaxRoot(root.ReplaceNode(fieldNode, newNode));
     return Task.FromResult(newDocument);
 }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:7,代码来源:CA2235CodeFixProviderBase.cs

示例6: FixEquals

 protected override async Task<Document> FixEquals(Document document, SyntaxGenerator generator, SyntaxNode root, SyntaxNode node, CancellationToken cancellationToken)
 {
     SemanticModel model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
     var binaryExpression = (BinaryExpressionSyntax)node;
     SyntaxNode invocation = CreateEqualsExpression(generator, model, binaryExpression.Left, binaryExpression.Right, node.Kind() == SyntaxKind.EqualsExpression).WithAdditionalAnnotations(Formatter.Annotation);
     SyntaxNode newRoot = root.ReplaceNode(node, invocation);
     return document.WithSyntaxRoot(newRoot);
 }
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:8,代码来源:CSharpUseOrdinalStringComparison.Fixer.cs

示例7: Fix

        private static async Task<Document> Fix(CodeFixContext context, SyntaxNode root, SyntaxGenerator generator, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            SyntaxNode node = root.FindNode(context.Span);
            Diagnostic diagnostic = context.Diagnostics.First();
            switch (diagnostic.Properties[OperatorOverloadsHaveNamedAlternatesAnalyzer.DiagnosticKindText])
            {
                case OperatorOverloadsHaveNamedAlternatesAnalyzer.AddAlternateText:
                    SyntaxNode methodDeclaration = generator.GetDeclaration(node, DeclarationKind.Operator) ?? generator.GetDeclaration(node, DeclarationKind.ConversionOperator);
                    var operatorOverloadSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken);
                    INamedTypeSymbol typeSymbol = operatorOverloadSymbol.ContainingType;

                    // For C# the following `typeDeclarationSyntax` and `typeDeclaration` nodes are identical, but for VB they're different so in
                    // an effort to keep this as language-agnostic as possible, the heavy-handed approach is used.
                    SyntaxNode typeDeclarationSyntax = typeSymbol.DeclaringSyntaxReferences.First().GetSyntax(cancellationToken);
                    SyntaxNode typeDeclaration = generator.GetDeclaration(typeDeclarationSyntax, DeclarationKind.Class);

                    SyntaxNode addedMember;
                    ImmutableArray<SyntaxNode> bodyStatements = ImmutableArray.Create(
                        generator.ThrowStatement(generator.ObjectCreationExpression(semanticModel.Compilation.GetTypeByMetadataName("System.NotImplementedException"))));
                    if (OperatorOverloadsHaveNamedAlternatesAnalyzer.IsPropertyExpected(operatorOverloadSymbol.Name))
                    {
                        // add a property
                        addedMember = generator.PropertyDeclaration(
                            name: OperatorOverloadsHaveNamedAlternatesAnalyzer.IsTrueText,
                            type: generator.TypeExpression(SpecialType.System_Boolean),
                            accessibility: Accessibility.Public,
                            modifiers: DeclarationModifiers.ReadOnly,
                            getAccessorStatements: bodyStatements);
                    }
                    else
                    {
                        // add a method
                        ExpectedMethodSignature expectedSignature = GetExpectedMethodSignature(operatorOverloadSymbol, semanticModel.Compilation);
                        addedMember = generator.MethodDeclaration(
                            name: expectedSignature.Name,
                            parameters: expectedSignature.Parameters.Select(p => generator.ParameterDeclaration(p.Item1, generator.TypeExpression(p.Item2))),
                            returnType: generator.TypeExpression(expectedSignature.ReturnType),
                            accessibility: Accessibility.Public,
                            modifiers: expectedSignature.IsStatic ? DeclarationModifiers.Static : DeclarationModifiers.None,
                            statements: bodyStatements);
                    }

                    SyntaxNode newTypeDeclaration = generator.AddMembers(typeDeclaration, addedMember);
                    return context.Document.WithSyntaxRoot(root.ReplaceNode(typeDeclaration, newTypeDeclaration));
                case OperatorOverloadsHaveNamedAlternatesAnalyzer.FixVisibilityText:
                    SyntaxNode badVisibilityNode = generator.GetDeclaration(node, DeclarationKind.Method) ?? generator.GetDeclaration(node, DeclarationKind.Property);
                    ISymbol badVisibilitySymbol = semanticModel.GetDeclaredSymbol(badVisibilityNode, cancellationToken);
                    SymbolEditor symbolEditor = SymbolEditor.Create(context.Document);
                    ISymbol newSymbol = await symbolEditor.EditOneDeclarationAsync(badVisibilitySymbol,
                        (documentEditor, syntaxNode) => documentEditor.SetAccessibility(badVisibilityNode, Accessibility.Public)).ConfigureAwait(false);
                    Document newDocument = symbolEditor.GetChangedDocuments().Single();
                    SyntaxNode newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
                    return context.Document.WithSyntaxRoot(newRoot);
                default:
                    return context.Document;
            }
        }
开发者ID:duracellko,项目名称:roslyn-analyzers,代码行数:57,代码来源:OperatorOverloadsHaveNamedAlternates.Fixer.cs

示例8: RoslynGenerator

        public RoslynGenerator(Job job)
        {
            _namespace = job.DestinationNamespace;
            _customAnnotations = job.CustomAnnotations;
            _nullableClasses = job.NullableClasses;

            _workspace = new AdhocWorkspace();
            _generator = SyntaxGenerator.GetGenerator(_workspace, LanguageNames.CSharp);
        }
开发者ID:mholo65,项目名称:ProtobufGenerator,代码行数:9,代码来源:RoslynGenerator.cs

示例9: RemoveFlagsAttribute

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

            AttributeData flagsAttribute = enumType.GetAttributes().First(a => a.AttributeClass == flagsAttributeType);
            SyntaxNode attributeNode = flagsAttribute.ApplicationSyntaxReference.GetSyntax(cancellationToken);

            return generator.RemoveNode(enumTypeSyntax, attributeNode);
        }
开发者ID:bkoelman,项目名称:roslyn-analyzers,代码行数:10,代码来源:EnumWithFlagsAttribute.Fixer.cs

示例10: GetExplicitlyAssignedField

        private SyntaxNode GetExplicitlyAssignedField(IFieldSymbol originalField, SyntaxNode declaration, SyntaxGenerator generator)
        {
            SyntaxNode originalInitializer = generator.GetExpression(declaration);
            if (originalInitializer != null || !originalField.HasConstantValue)
            {
                return declaration;
            }

            return generator.WithExpression(declaration, generator.LiteralExpression(originalField.ConstantValue));
        }
开发者ID:duracellko,项目名称:roslyn-analyzers,代码行数:10,代码来源:EnumsShouldHaveZeroValue.Fixer.cs

示例11: AddSerializableAttributeToType

        private static async Task<Solution> AddSerializableAttributeToType(Document document, SemanticModel model, SyntaxGenerator generator, ITypeSymbol type, CancellationToken cancellationToken)
        {
            var typeDeclNode = type.DeclaringSyntaxReferences.First().GetSyntax(cancellationToken);

            var serializableAttr = generator.Attribute(generator.TypeExpression(WellKnownTypes.SerializableAttribute(model.Compilation)));
            var newTypeDeclNode = generator.AddAttributes(typeDeclNode, serializableAttr);
            var documentContainingNode = document.Project.Solution.GetDocument(typeDeclNode.SyntaxTree);
            var docRoot = await documentContainingNode.GetSyntaxRootAsync(cancellationToken);
            var newDocumentContainingNode = documentContainingNode.WithSyntaxRoot(docRoot.ReplaceNode(typeDeclNode, newTypeDeclNode));
            return newDocumentContainingNode.Project.Solution;
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:11,代码来源:CA2235CodeFixProviderBase.cs

示例12: TimeSpanParameterConverter

        public TimeSpanParameterConverter(SemanticModel semanticModel, SyntaxGenerator syntaxGenerator)
        {
            if (semanticModel == null)
            throw new ArgumentNullException("semanticModel", "semanticModel is null.");

             if (syntaxGenerator == null)
            throw new ArgumentNullException("syntaxGenerator", "syntaxGenerator is null.");

             m_syntaxGenerator = syntaxGenerator;
             m_semanticModel = semanticModel;
        }
开发者ID:modulexcite,项目名称:EventSourceGenerator,代码行数:11,代码来源:TimeSpanParameterConversion.cs

示例13: FixArgument

        protected override Task<Document> FixArgument(Document document, SyntaxGenerator generator, SyntaxNode root, SyntaxNode argument)
        {
            var memberAccess = ((ArgumentSyntax)argument)?.Expression as MemberAccessExpressionSyntax;
            if (memberAccess != null)
            {
                // preserve the "IgnoreCase" suffix if present
                bool isIgnoreCase = memberAccess.Name.GetText().ToString().EndsWith(UseOrdinalStringComparisonAnalyzer.IgnoreCaseText, StringComparison.Ordinal);
                string newOrdinalText = isIgnoreCase ? UseOrdinalStringComparisonAnalyzer.OrdinalIgnoreCaseText : UseOrdinalStringComparisonAnalyzer.OrdinalText;
                SyntaxNode newIdentifier = generator.IdentifierName(newOrdinalText);
                MemberAccessExpressionSyntax newMemberAccess = memberAccess.WithName((SimpleNameSyntax)newIdentifier).WithAdditionalAnnotations(Formatter.Annotation);
                SyntaxNode newRoot = root.ReplaceNode(memberAccess, newMemberAccess);
                return Task.FromResult(document.WithSyntaxRoot(newRoot));
            }

            return Task.FromResult(document);
        }
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:16,代码来源:CSharpUseOrdinalStringComparison.Fixer.cs

示例14: SyntaxEditor

        /// <summary>
        /// Creates a new <see cref="SyntaxEditor"/> instance.
        /// </summary>
        public SyntaxEditor(SyntaxNode root, Workspace workspace)
        {
            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            if (workspace == null)
            {
                throw new ArgumentNullException(nameof(workspace));
            }

            _root = root;
            _generator = SyntaxGenerator.GetGenerator(workspace, root.Language);
            _changes = new List<Change>();
        }
开发者ID:RoryVL,项目名称:roslyn,代码行数:19,代码来源:SyntaxEditor.cs

示例15: InsertNamespaceImport

        protected override SyntaxNode InsertNamespaceImport(SyntaxNode root, SyntaxGenerator gen, SyntaxNode import, OptionSet options)
        {
            var comparer = options.GetOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp)
                    ? UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance
                    : UsingsAndExternAliasesDirectiveComparer.NormalInstance;

            // find insertion point
            foreach (var existingImport in gen.GetNamespaceImports(root))
            {
                if (comparer.Compare(import, existingImport) < 0)
                {
                    return gen.InsertNodesBefore(root, existingImport, new[] { import });
                }
            }

            return gen.AddNamespaceImports(root, import);
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:17,代码来源:CSharpImportAdder.cs


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