本文整理汇总了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);
}
示例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));
}
示例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);
}
}
示例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));
}
示例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);
}
示例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);
}
示例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;
}
}
示例8: RoslynGenerator
public RoslynGenerator(Job job)
{
_namespace = job.DestinationNamespace;
_customAnnotations = job.CustomAnnotations;
_nullableClasses = job.NullableClasses;
_workspace = new AdhocWorkspace();
_generator = SyntaxGenerator.GetGenerator(_workspace, LanguageNames.CSharp);
}
示例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);
}
示例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));
}
示例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;
}
示例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;
}
示例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);
}
示例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>();
}
示例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);
}