• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# SyntaxGenerator类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: GetFix

        private Task<Document> GetFix(Document document, SyntaxNode root, SyntaxNode classDecl, SyntaxGenerator generator, params string[] languages)
        {
            var languageNamesFullName = typeof(LanguageNames).FullName;
            var arguments = new SyntaxNode[languages.Length];

            for (int i = 0; i < languages.Length; i++)
            {
                var language = languages[i] == LanguageNames.CSharp ? nameof(LanguageNames.CSharp) : nameof(LanguageNames.VisualBasic);
                var expressionToParse = languageNamesFullName + "." + language;
                var parsedExpression = ParseExpression(expressionToParse);
                arguments[i] = generator.AttributeArgument(parsedExpression);
            }

            SyntaxNode attribute = generator.Attribute(DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticAnalyzerAttributeFullName, arguments);
            var newClassDecl = generator.AddAttributes(classDecl, attribute);
            var newRoot = root.ReplaceNode(classDecl, newClassDecl);
            return Task.FromResult(document.WithSyntaxRoot(newRoot));
        }
开发者ID:GloryChou,项目名称:roslyn,代码行数:18,代码来源:ApplyDiagnosticAnalyzerAttributeFix.cs


示例17: FixIdentifierName

        protected override async Task<Document> FixIdentifierName(Document document, SyntaxGenerator generator, SyntaxNode root, SyntaxNode identifier, CancellationToken cancellationToken)
        {
            InvocationExpressionSyntax invokeParent = identifier?.Parent?.FirstAncestorOrSelf<InvocationExpressionSyntax>();
            if (invokeParent != null)
            {
                SemanticModel model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
                var methodSymbol = model.GetSymbolInfo((IdentifierNameSyntax)identifier, cancellationToken).Symbol as IMethodSymbol;
                if (methodSymbol != null && CanAddStringComparison(methodSymbol, model))
                {
                    // append a new StringComparison.Ordinal argument
                    SyntaxNode newArg = generator.Argument(CreateOrdinalMemberAccess(generator, model))
                        .WithAdditionalAnnotations(Formatter.Annotation);
                    InvocationExpressionSyntax newInvoke = invokeParent.AddArgumentListArguments((ArgumentSyntax)newArg).WithAdditionalAnnotations(Formatter.Annotation);
                    SyntaxNode newRoot = root.ReplaceNode(invokeParent, newInvoke);
                    return document.WithSyntaxRoot(newRoot);
                }
            }

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


示例18: GenerateThrowStatement

		public static SyntaxNode GenerateThrowStatement(
			SyntaxGenerator factory,
			SemanticDocument document,
			string exceptionMetadataName,
			CancellationToken cancellationToken)
		{
			var compilation = document.SemanticModel.Compilation;
			var exceptionType = compilation.GetTypeByMetadataName(exceptionMetadataName);

			// If we can't find the Exception, we obviously can't generate anything.
			if (exceptionType == null)
			{
				return null;
			}

			var exceptionCreationExpression = factory.ObjectCreationExpression(
				exceptionType,
				SpecializedCollections.EmptyList<SyntaxNode>());

			return factory.ThrowStatement(exceptionCreationExpression);
		}
开发者ID:pabloescribanoloza,项目名称:monodevelop,代码行数:21,代码来源:CodeGenerationHelpers.cs


示例19: GenerateProxyInterface

      public InterfaceDeclarationSyntax GenerateProxyInterface(SemanticModel semanticModel, SyntaxGenerator generator, INamedTypeSymbol sourceServiceInterface, string targetInterfaceName, Accessibility accessibility = Accessibility.Public, bool inheritServiceInterface = false, bool suppressAsyncMethodGeneration = false, bool suppressWarningComments = false)
      {
         SyntaxNode targetInterface = generator.InterfaceDeclaration(targetInterfaceName, accessibility: accessibility);

         targetInterface = generator.AddAttributes(targetInterface, sourceServiceInterface.GetAttributes().Select(attr => generator.Attribute(attr)));

         foreach (SyntaxNode method in GetOperationContractMethodDeclarations(semanticModel, generator, sourceServiceInterface, true, !inheritServiceInterface, suppressAsyncMethodGeneration))
         {
            targetInterface = generator.AddMembers(targetInterface, generator.AddWarningCommentIf(!suppressWarningComments, method));
         }

         if (inheritServiceInterface)
         {
            targetInterface = generator.AddInterfaceType(targetInterface, generator.TypeExpression(sourceServiceInterface));
         }

         targetInterface = AddGeneratedCodeAttribute(generator, targetInterface);

         targetInterface = generator.AddWarningCommentIf(!suppressWarningComments, targetInterface);

         return (InterfaceDeclarationSyntax)targetInterface;
      }
开发者ID:modulexcite,项目名称:WcfClientProxyGenerator,代码行数:22,代码来源:ClientProxyGenerator.ProxyInterface.cs


示例20: CreateEqualsExpression

        internal SyntaxNode CreateEqualsExpression(SyntaxGenerator syntaxFactoryService, SemanticModel model, SyntaxNode operand1, SyntaxNode operand2, bool isEquals)
        {
            var stringType = model.Compilation.GetSpecialType(SpecialType.System_String);
            var memberAccess = syntaxFactoryService.MemberAccessExpression(
                        syntaxFactoryService.TypeExpression(stringType),
                        syntaxFactoryService.IdentifierName(UseOrdinalStringComparisonAnalyzer.EqualsMethodName));
            var ordinal = CreateOrdinalMemberAccess(syntaxFactoryService, model);
            var invocation = syntaxFactoryService.InvocationExpression(
                memberAccess,
                operand1,
                operand2.WithoutTrailingTrivia(),
                ordinal)
                .WithAdditionalAnnotations(Formatter.Annotation);
            if (!isEquals)
            {
                invocation = syntaxFactoryService.LogicalNotExpression(invocation);
            }

            invocation = invocation.WithTrailingTrivia(operand2.GetTrailingTrivia());

            return invocation;
        }
开发者ID:maggiemsft,项目名称:roslyn-analyzers,代码行数:22,代码来源:UseOrdinalStringComparison.Fixer.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# SyntaxKind类代码示例发布时间:2022-05-24
下一篇:
C# SyntaxContext类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap