本文整理汇总了C#中SyntaxGenerator.LiteralExpression方法的典型用法代码示例。如果您正苦于以下问题:C# SyntaxGenerator.LiteralExpression方法的具体用法?C# SyntaxGenerator.LiteralExpression怎么用?C# SyntaxGenerator.LiteralExpression使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SyntaxGenerator
的用法示例。
在下文中一共展示了SyntaxGenerator.LiteralExpression方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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));
}
示例2: CreateEmptyRule
internal static FieldDeclarationSyntax CreateEmptyRule(SyntaxGenerator generator, string idName="Change me to the name of the above constant", string titleDefault="Enter a title for this diagnostic", string messageDefault="Enter a message to be displayed with this diagnostic",
string categoryDefault="Enter a category for this diagnostic (e.g. Formatting)", ExpressionSyntax severityDefault=null, ExpressionSyntax enabledDefault=null)
{
if (severityDefault == null)
{
severityDefault = generator.DefaultExpression(SyntaxFactory.ParseTypeName("DiagnosticSeverity")) as ExpressionSyntax;
}
if (enabledDefault == null)
{
enabledDefault = generator.DefaultExpression(generator.TypeExpression(SpecialType.System_Boolean)) as ExpressionSyntax;
}
var type = SyntaxFactory.ParseTypeName("DiagnosticDescriptor");
var arguments = new ArgumentSyntax[6];
var whitespace = " ";
var id = generator.LiteralExpression(idName);
var idArg = generator.Argument("id", RefKind.None, id).WithLeadingTrivia(SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.Whitespace(whitespace)) as ArgumentSyntax;
arguments[0] = idArg;
var title = generator.LiteralExpression(titleDefault);
var titleArg = generator.Argument("title", RefKind.None, title).WithLeadingTrivia(SyntaxFactory.Whitespace(whitespace)) as ArgumentSyntax;
arguments[1] = titleArg;
var message = generator.LiteralExpression(messageDefault);
var messageArg = generator.Argument("messageFormat", RefKind.None, message).WithLeadingTrivia(SyntaxFactory.Whitespace(whitespace)) as ArgumentSyntax;
arguments[2] = messageArg;
var category = generator.LiteralExpression(categoryDefault);
var categoryArg = generator.Argument("category", RefKind.None, category).WithLeadingTrivia(SyntaxFactory.Whitespace(whitespace)) as ArgumentSyntax;
arguments[3] = categoryArg;
var defaultSeverityArg = generator.Argument("defaultSeverity", RefKind.None, severityDefault).WithLeadingTrivia(SyntaxFactory.Whitespace(whitespace)) as ArgumentSyntax;
arguments[4] = defaultSeverityArg;
var enabledArg = generator.Argument("isEnabledByDefault", RefKind.None, enabledDefault).WithLeadingTrivia(SyntaxFactory.Whitespace(whitespace)) as ArgumentSyntax;
arguments[5] = enabledArg;
var identifier = SyntaxFactory.ParseToken("spacingRule");
var separators = new List<SyntaxToken>();
var separator = SyntaxFactory.ParseToken(",").WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed);
separators.Add(separator);
separators.Add(separator);
separators.Add(separator);
separators.Add(separator);
separators.Add(separator);
var argumentsNewLines = SyntaxFactory.SeparatedList(arguments, separators);
var argumentList = SyntaxFactory.ArgumentList(argumentsNewLines);
var value = SyntaxFactory.ObjectCreationExpression(type, argumentList, null);
var initializer = SyntaxFactory.EqualsValueClause(value);
var variables = new SeparatedSyntaxList<VariableDeclaratorSyntax>();
var variable = SyntaxFactory.VariableDeclarator(identifier, null, initializer);
variables = variables.Add(variable);
var declaration = SyntaxFactory.VariableDeclaration(type.WithTrailingTrivia(SyntaxFactory.Whitespace(" ")), variables);
var modifiers = SyntaxFactory.TokenList(SyntaxFactory.ParseToken("internal").WithTrailingTrivia(SyntaxFactory.Whitespace(" ")), SyntaxFactory.ParseToken("static").WithTrailingTrivia(SyntaxFactory.Whitespace(" ")));
var rule = SyntaxFactory.FieldDeclaration(new SyntaxList<AttributeListSyntax>(), modifiers, declaration);
return rule;
}
示例3: WhitespaceCheckHelper
internal static SyntaxNode WhitespaceCheckHelper(SyntaxGenerator generator, IfStatementSyntax ifStatement, SyntaxList<SyntaxNode> ifBlockStatements)
{
var ifOneBlock = ifStatement.Parent as BlockSyntax;
var ifTwoBlock = ifStatement.Statement as BlockSyntax;
var trailingTriviaDeclaration = ifOneBlock.Statements[0] as LocalDeclarationStatementSyntax;
var trailingTrivia = generator.IdentifierName(trailingTriviaDeclaration.Declaration.Variables[0].Identifier.ValueText);
var arguments = new SyntaxList<SyntaxNode>();
var trailingTriviaToString = generator.InvocationExpression(generator.MemberAccessExpression(trailingTrivia, "ToString"), arguments);
var rightSide = generator.LiteralExpression(" ");
var equalsExpression = generator.ValueEqualsExpression(trailingTriviaToString, rightSide);
var newIfStatement = generator.IfStatement(equalsExpression, ifBlockStatements);
return newIfStatement;
}
示例4: TriviaCountHelper
internal static SyntaxNode TriviaCountHelper(SyntaxGenerator generator, string name, SyntaxList<StatementSyntax> ifBlockStatements)
{
var variableName = generator.IdentifierName(name);
var memberAccess = generator.MemberAccessExpression(variableName, "TrailingTrivia");
var fullMemberAccess = generator.MemberAccessExpression(memberAccess, "Count");
var one = generator.LiteralExpression(1);
var equalsExpression = generator.ValueEqualsExpression(fullMemberAccess, one);
var newIfStatement = generator.IfStatement(equalsExpression, ifBlockStatements);
return newIfStatement;
}
示例5: NewIdCreator
// creates a new id with the provided name as a literal expression
protected internal static SyntaxNode NewIdCreator(SyntaxGenerator generator, string fieldName, string idName)
{
SyntaxNode initializer = generator.LiteralExpression(idName);
SyntaxNode newField = generator.FieldDeclaration(fieldName, generator.TypeExpression(SpecialType.System_String), Accessibility.Public, DeclarationModifiers.Const, initializer);
return newField;
}
示例6: WhitespaceCheckHelper
// creates the whitespace check
protected internal static SyntaxNode WhitespaceCheckHelper(SyntaxGenerator generator, IfStatementSyntax ifStatement, SyntaxList<SyntaxNode> ifBlockStatements)
{
var ifBlock = ifStatement.Parent as BlockSyntax;
string variableName = GetTrailingTriviaName(ifBlock);
SyntaxNode identifierName = generator.IdentifierName(variableName);
var arguments = new SyntaxList<SyntaxNode>();
SyntaxNode trailingTriviaToString = generator.InvocationExpression(generator.MemberAccessExpression(identifierName, "ToString"), arguments);
SyntaxNode rightSide = generator.LiteralExpression(" ");
SyntaxNode equalsExpression = generator.ValueEqualsExpression(trailingTriviaToString, rightSide);
SyntaxNode newIfStatement = generator.IfStatement(equalsExpression, ifBlockStatements);
return newIfStatement;
}
示例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,
typeSymbol.TypeKind == TypeKind.Struct ? DeclarationKind.Struct : DeclarationKind.Class);
SyntaxNode addedMember;
IEnumerable<SyntaxNode> bodyStatements = generator.DefaultMethodBody(semanticModel.Compilation);
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);
if (expectedSignature.Name == "CompareTo" && operatorOverloadSymbol.ContainingType.TypeKind == TypeKind.Class)
{
var nullCheck = generator.IfStatement(
generator.InvocationExpression(
generator.IdentifierName("ReferenceEquals"),
generator.IdentifierName(expectedSignature.Parameters.First().Item1),
generator.NullLiteralExpression()),
new[]
{
generator.ReturnStatement(generator.LiteralExpression(1))
});
bodyStatements = new[] {nullCheck}.Concat(bodyStatements);
}
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), cancellationToken).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: GetMethodStatementsSyntax
private static IEnumerable<SyntaxNode> GetMethodStatementsSyntax(
SyntaxGenerator syntaxGenerator,
SemanticModel semanticModel,
IMethodSymbol methodSymbol)
{
// GENERATED CODE (for every ref or out parameter):
//
// string someOutParameter;
// var someRefParameter = default(int);
for (var i = 0; i < methodSymbol.Parameters.Length; ++i)
{
var parameter = methodSymbol.Parameters[i];
if (parameter.RefKind == RefKind.Out)
{
yield return syntaxGenerator
.LocalDeclarationStatement(
syntaxGenerator.TypeExpression(parameter.Type),
GetNameForParameter(methodSymbol, parameter));
}
else if (parameter.RefKind == RefKind.Ref)
{
yield return syntaxGenerator
.LocalDeclarationStatement(
GetNameForParameter(methodSymbol, parameter),
initializer: syntaxGenerator.DefaultExpression(syntaxGenerator.TypeExpression(parameter.Type)));
}
}
var arguments = methodSymbol
.Parameters
.Select(x =>
syntaxGenerator
.Argument(
x.RefKind,
syntaxGenerator.IdentifierName(GetNameForParameter(methodSymbol, x))))
.ToList();
var typeArguments = methodSymbol
.TypeArguments
.Select(x => syntaxGenerator.TypeExpression(x))
.ToList();
var lambdaParameterName = GetUniqueName(methodSymbol);
var lambdaInvocation = syntaxGenerator
.MemberAccessExpression(
syntaxGenerator.IdentifierName(lambdaParameterName),
methodSymbol.Name);
if (typeArguments.Count > 0)
{
lambdaInvocation = syntaxGenerator
.WithTypeArguments(
lambdaInvocation,
typeArguments);
}
// GENERATED CODE (for every ref or out parameter):
//
// someOutParameter = this.GetOutParameterValue<string>(x => x.TheMethod(out someOutParameter), parameterIndex: 0);
// someRefParameter = this.GetRefParameterValue<int>(x => x.TheMethod(ref someRefParameter), parameterIndex: 0);
for (var i = 0; i < methodSymbol.Parameters.Length; ++i)
{
var parameter = methodSymbol.Parameters[i];
if (parameter.RefKind == RefKind.Out || parameter.RefKind == RefKind.Ref)
{
var nameOfMethodToCall = parameter.RefKind == RefKind.Out ? "GetOutParameterValue" : "GetRefParameterValue";
yield return syntaxGenerator
.AssignmentStatement(
syntaxGenerator.IdentifierName(parameter.Name),
syntaxGenerator
.InvocationExpression(
syntaxGenerator.MemberAccessExpression(
syntaxGenerator.ThisExpression(),
syntaxGenerator.GenericName(
nameOfMethodToCall,
typeArguments: syntaxGenerator.TypeExpression(parameter.Type))),
arguments: new[]
{
syntaxGenerator.ValueReturningLambdaExpression(
lambdaParameterName,
syntaxGenerator.InvocationExpression(
lambdaInvocation,
arguments: arguments)),
syntaxGenerator.LiteralExpression(i)
}));
}
}
// GENERATED CODE:
//
// [return] this.Apply(x => x.SomeMethod(param1, param2));
var applyInvocation = syntaxGenerator
.InvocationExpression(
syntaxGenerator.MemberAccessExpression(
syntaxGenerator.ThisExpression(),
"Apply"),
//.........这里部分代码省略.........
示例9: GetClassAttributesSyntax
private static IEnumerable<SyntaxNode> GetClassAttributesSyntax(
SyntaxGenerator syntaxGenerator,
SemanticModel semanticModel)
{
// GENERATED CODE:
//
// [System.CodeDom.Compiler.GeneratedCode("PCLMock", "[version]")]
// [System.Runtime.CompilerServices.CompilerGenerated)]
yield return syntaxGenerator
.Attribute(
"System.CodeDom.Compiler.GeneratedCode",
syntaxGenerator.LiteralExpression("PCLMock"),
syntaxGenerator.LiteralExpression(typeof(MockBase<>).Assembly.GetName().Version.ToString()));
yield return syntaxGenerator
.Attribute(
"System.Runtime.CompilerServices.CompilerGenerated");
}