public static bool Applicable(SemanticModel semanticModel, ArgumentSyntax argument, IEnumerable<ParameterSyntax> parameters) { var symbolInfo = semanticModel.GetSymbolInfo(argument.Expression); var symbol = symbolInfo.Symbol; if (symbol == null) { return true; } if (symbol.Kind != SymbolKind.Field && symbol.Kind != SymbolKind.Parameter && symbol.Kind != SymbolKind.Local) { return false; } var field = symbol as IFieldSymbol; if (field != null) { return !field.IsReadOnly; } return true; }
private async Task<Document> UseDeclarationExpression(Document document, ArgumentSyntax argument, VariableDeclaratorSyntax declarator, CancellationToken cancellationToken) { // get variable declaration var declaration = declarator.Parent; // get statement which contains both local declaration statement and method call with out argument var statement = DiagnosticAnalyzer.GetContainingStatement(declaration.Parent); // remove entire local declaration statement or just single variable declaration // depending on how many variables are declared within single local declaration statement var nodeToRemove = declaration.ChildNodes().OfType<VariableDeclaratorSyntax>().Count() > 1 ? declarator : declaration.Parent; var newStatement = statement.RemoveNode(nodeToRemove, SyntaxRemoveOptions.KeepEndOfLine); // get variable type var type = declaration.ChildNodes().First() as TypeSyntax; // create new Declaration Expression using variable type and declarator var newDeclarationExpression = SyntaxFactory.DeclarationExpression(type, declarator); // fix the trivia aroung Declaration Expression var firstToken = newDeclarationExpression.GetFirstToken(); var leadingTrivia = firstToken.LeadingTrivia; var trimmedDeclarationExpression = newDeclarationExpression.ReplaceToken(firstToken, firstToken.WithLeadingTrivia(SyntaxTriviaList.Empty)); // get ArgumentSyntax from newStatement which is equivalent to argument from original syntax tree var newArgument = newStatement.DescendantNodes() .FirstOrDefault(n => n.IsEquivalentTo(argument)); // replace argument with new version, containing Declaration Expression newStatement = newStatement.ReplaceNode(newArgument.ChildNodes().First(), trimmedDeclarationExpression); // get root for current document and replace statement with new version var root = await document.GetSyntaxRootAsync(cancellationToken); var newRoot = root.ReplaceNode(statement, newStatement); // return document with modified syntax return document.WithSyntaxRoot(newRoot); }
public static IParameterSymbol GetParameterSymbol(ArgumentSyntax argument, ArgumentListSyntax argumentList, IMethodSymbol method) { if (!argumentList.Arguments.Contains(argument) || method == null) { return null; } if (argument.NameColon != null) { return method.Parameters .FirstOrDefault(symbol => symbol.Name == argument.NameColon.Name.Identifier.ValueText); } var argumentIndex = argumentList.Arguments.IndexOf(argument); var parameterIndex = argumentIndex; if (parameterIndex >= method.Parameters.Length) { var p = method.Parameters.Last(); return p.IsParams ? p : null; } var parameter = method.Parameters[parameterIndex]; return parameter; }
public static bool TryGetParameterSymbol(ArgumentSyntax argument, ArgumentListSyntax argumentList, IMethodSymbol method, out IParameterSymbol parameter) { parameter = null; if (!argumentList.Arguments.Contains(argument) || method == null || method.IsVararg) { return false; } if (argument.NameColon != null) { parameter = method.Parameters .FirstOrDefault(symbol => symbol.Name == argument.NameColon.Name.Identifier.ValueText); return parameter != null; } var argumentIndex = argumentList.Arguments.IndexOf(argument); var parameterIndex = argumentIndex; if (parameterIndex >= method.Parameters.Length) { var lastParameter = method.Parameters.Last(); parameter = lastParameter.IsParams ? lastParameter : null; return parameter != null; } parameter = method.Parameters[parameterIndex]; return true; }
private async Task<Document> FormatXmlAsync(Document document, ArgumentSyntax argSntax, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken); var tree = root.SyntaxTree; //Get the character position of the ArgumentSyntax FileLinePositionSpan position = tree.GetLineSpan(argSntax.Span); int cSpace = position.StartLinePosition.Character; //Get the parent VariableDeclaration to figure out the preceeding trivia since we can't //get the column position from GetLineSpan (bug?) var parent = argSntax.Ancestors().Where(t => t.IsKind(SyntaxKind.VariableDeclaration)).FirstOrDefault(); var parentTrivia = parent.GetLeadingTrivia().ToFullString(); var xml = argSntax.Expression.GetFirstToken().ValueText; var newXml = FormatXml(xml); //Process each line of the formatted XML and prepend the parent trivia & spaces string[] xmlLines = newXml.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); for (int i = 1; i < xmlLines.Length; i++) { xmlLines[i] = parentTrivia + new String(' ', (cSpace - 14)) + xmlLines[i]; } newXml = String.Join("\r\n", xmlLines); newXml = "@\"" + newXml + "\""; var newNode = SyntaxFactory.Argument(null, SyntaxFactory.Token(SyntaxKind.None), SyntaxFactory.IdentifierName(newXml)); var newRoot = root.ReplaceNode(argSntax, newNode); return document.WithSyntaxRoot(newRoot); }
public override SyntaxNode VisitArgument(ArgumentSyntax node) { var invocationSyntax = node.Parent.Parent as InvocationExpressionSyntax; if(invocationSyntax == null) return base.VisitArgument(node); var memberAccessExpressionSyntax = invocationSyntax.Expression as MemberAccessExpressionSyntax; if(memberAccessExpressionSyntax == null) return base.VisitArgument(node); var methodNameSyntax = memberAccessExpressionSyntax.Name as SimpleNameSyntax; var method = model.GetSymbolInfo(methodNameSyntax).Symbol as IMethodSymbol; if(method == null) return base.VisitArgument(node); var argList = (ArgumentListSyntax)node.Parent; //TODO check that parameter name preserved if specified, otherwise order can be broken var argIndex = argList.Arguments.IndexOf(node); var parameterSymbol = method.Parameters[argIndex]; //TODO when there is params argument in method index may be well out of range var lambda = node.Expression as LambdaExpressionSyntax; if(parameterSymbol.HasAttribute<MetaRewriteLambdaParamAttribute>(model.Compilation) && lambda != null) { //TODO error if value is not lambda return node.WithExpression(VisitLambdaExpression(lambda)); } if(parameterSymbol.HasAttribute<MetaRewriteParamAttribute>(model.Compilation)) return node.WithExpression(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(node.Expression.ToFullString()))); return base.VisitArgument(node); }
static InvocationExpressionSyntax CheckThat(INamedTypeSymbol nfluentCheck, ArgumentSyntax argument) { return InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, nfluentCheck.ToNameSyntax(), IdentifierName("That")), ArgumentList(SingletonSeparatedList(argument))); }
private static bool IsOrdinalOrOrdinalIgnoreCase(ArgumentSyntax argumentSyntax, SemanticModel model) { var argumentSymbol = model.GetSymbolInfo(argumentSyntax.Expression).Symbol; if (argumentSymbol != null) { return IsOrdinalOrOrdinalIgnoreCase(argumentSymbol.Name); } return false; }
public static string Argument(ArgumentSyntax arg) { var output = SyntaxNode(arg.Expression); if (arg.NameColon != null) { output = SyntaxNode(arg.NameColon.Name) + ": " + output; } return output; }
public AddOutOrRefCodeAction( Document document, SemanticModel semanticModel, ArgumentSyntax argument, IEnumerable<ParameterSyntax> parameters) { this.document = document; this.semanticModel = semanticModel; this.argument = argument; this.parameters = parameters; }
public override VisualBasicSyntaxNode VisitArgument(CSS.ArgumentSyntax node) { NameColonEqualsSyntax name = null; if (node.NameColon != null) { name = SyntaxFactory.NameColonEquals((IdentifierNameSyntax)node.NameColon.Name.Accept(this)); } var value = (ExpressionSyntax)node.Expression.Accept(this); return(SyntaxFactory.SimpleArgument(name, value)); }
protected ITypeSymbol GetArgumentType(ArgumentSyntax syntax) { var symbol = this.semanticModel.GetSpeculativeSymbolInfo(syntax.Expression.SpanStart + this.displacement, syntax.Expression, SpeculativeBindingOption.BindAsExpression).Symbol; var property = symbol?.GetType().GetProperty("Type"); if (property != null) { return property.GetValue(symbol) as ITypeSymbol; } return this.semanticModel.GetSpeculativeTypeInfo(syntax.Expression.SpanStart + this.displacement, syntax.Expression, SpeculativeBindingOption.BindAsExpression).Type; }
/// <summary> /// Lifts the expression represented by <paramref name="argument" />, if necessary. /// </summary> public override SyntaxNode VisitArgument(ArgumentSyntax argument) { if (argument.Parent.Parent is ElementAccessExpressionSyntax) return base.VisitArgument(argument); var requiresLifting = argument.HasAttribute<LiftExpressionAttribute>(SemanticModel); argument = (ArgumentSyntax)base.VisitArgument(argument); if (!requiresLifting) return argument; var expression = SyntaxBuilder.Lambda(Enumerable.Empty<ParameterSyntax>(), argument.Expression).WithTrivia(argument); return argument.WithExpression(expression); }
private bool IsPassedToDelegateCreationExpression(ArgumentSyntax argument, ITypeSymbol type) { if (type.IsDelegateType() && argument.IsParentKind(SyntaxKind.ArgumentList) && argument.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression)) { var objectCreationExpression = (ObjectCreationExpressionSyntax)argument.Parent.Parent; var objectCreationType = _semanticModel.GetTypeInfo(objectCreationExpression).Type; if (objectCreationType.Equals(type)) { return true; } } return false; }
private Task<Document> ComputeRoot( Document document, SyntaxNode root, ArgumentSyntax argument, IMethodSymbol methodSymbol) { var providenArgumentsList = argument.Parent as ArgumentListSyntax; var providenArguments = providenArgumentsList.Arguments; var argumentIndex = providenArguments.IndexOf(argument); var newArguments = Enumerable.Concat( providenArguments.Take(argumentIndex), providenArguments.Skip(argumentIndex) .Select((arg, index) => { var parameterName = methodSymbol.Parameters[index].Name; return arg .WithNameColon(NameColon(IdentifierName(parameterName))) .WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation); })); var newArgumentList = providenArgumentsList.WithArguments(SeparatedList(newArguments)); var newRoot = root.ReplaceNode(providenArgumentsList, newArgumentList); return Task.FromResult(document.WithSyntaxRoot(newRoot)); }
private async Task<Document> DiagnosticSeverityError(Document document, ArgumentSyntax argument, CancellationToken c) { SyntaxGenerator generator = SyntaxGenerator.GetGenerator(document); SyntaxNode expression = generator.IdentifierName("DiagnosticSeverity"); var newExpression = generator.MemberAccessExpression(expression, "Error") as ExpressionSyntax; var rule = argument.FirstAncestorOrSelf<FieldDeclarationSyntax>(); var newRule = rule.ReplaceNode(argument.Expression, newExpression); return await ReplaceNode(argument.FirstAncestorOrSelf<FieldDeclarationSyntax>(), newRule.WithTrailingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.EndOfLine("\r\n"), SyntaxFactory.Whitespace(" "), SyntaxFactory.ParseTrailingTrivia("// defaultSeverity: Is set to DiagnosticSeverity.[severity] where severity can be Error, Warning, Hidden or Info, but can only be Error or Warning for the purposes of this tutorial").ElementAt(0), SyntaxFactory.EndOfLine("\r\n"))).WithLeadingTrivia(argument.FirstAncestorOrSelf<FieldDeclarationSyntax>().GetLeadingTrivia()), document); }
public static glsl.ArgumentSyntax Translate(this cs.ArgumentSyntax node) { return(new glsl.ArgumentSyntax().Update( node.Expression.Translate() )); }
private async Task<Document> EnabledByDefaultAsync(Document document, ArgumentSyntax argument, CancellationToken c) { SyntaxGenerator generator = SyntaxGenerator.GetGenerator(document); var rule = argument.FirstAncestorOrSelf<FieldDeclarationSyntax>(); var newRule = rule.ReplaceNode(argument.Expression, generator.LiteralExpression(true)); return await ReplaceNode(argument.FirstAncestorOrSelf<FieldDeclarationSyntax>(), newRule.WithTrailingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.EndOfLine("\r\n"), SyntaxFactory.Whitespace(" "), SyntaxFactory.ParseTrailingTrivia("// isEnabledByDefault: Determines whether the analyzer is enabled by default or if the user must manually enable it. Generally set to true").ElementAt(0), SyntaxFactory.EndOfLine("\r\n"))).WithLeadingTrivia(argument.FirstAncestorOrSelf<FieldDeclarationSyntax>().GetLeadingTrivia()), document); }
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; }
public override object ExtractArgumentValue(CSharpSyntax.ArgumentSyntax argumentSyntax) => Compiler.SemanticModel.GetConstantValue(argumentSyntax.Expression).Value;
public override SyntaxNode VisitArgument(ArgumentSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var newArgument = (ArgumentSyntax)base.VisitArgument(node); var argumentType = _semanticModel.GetTypeInfo(node.Expression).ConvertedType; if (argumentType != null && !IsPassedToDelegateCreationExpression(node, argumentType)) { ExpressionSyntax newArgumentExpressionWithCast; if (TryCastTo(argumentType, node.Expression, newArgument.Expression, out newArgumentExpressionWithCast)) { return newArgument.WithExpression(newArgumentExpressionWithCast); } } return newArgument; }
static SyntaxNode GetArgumentValue(ArgumentSyntax argument) { return argument.Expression; }
public ArgumentParameterMapping(ArgumentSyntax argument, IParameterSymbol parameter) { Argument = argument; Parameter = parameter; }
private IEnumerable<ITypeSymbol> InferTypeInArgument(int index, IEnumerable<IMethodSymbol> methods, ArgumentSyntax argumentOpt) { return InferTypeInArgument(index, methods.Select(m => m.Parameters), argumentOpt); }
static string FormatArgument(ArgumentSyntax argument) { return string.Format(@"new Nake.TaskArgument(""{0}"", {1})", GetArgumentName(argument), GetArgumentValue(argument)); }
private static InvocationExpressionSyntax GetIsInstanceOfTypeCall(InvocationExpressionSyntax invocation, ExpressionSyntax typeInstance, ArgumentSyntax getTypeCallInArgument) { return SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, typeInstance, SyntaxFactory.IdentifierName("IsInstanceOfType")).WithTriviaFrom(invocation.Expression), SyntaxFactory.ArgumentList( SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Argument( GetExpressionFromGetType(getTypeCallInArgument.Expression)).WithTriviaFrom(getTypeCallInArgument) })) .WithTriviaFrom(invocation.ArgumentList)) .WithTriviaFrom(invocation); }
private IEnumerable<ITypeSymbol> InferTypeInArgument( int index, IEnumerable<ImmutableArray<IParameterSymbol>> parameterizedSymbols, ArgumentSyntax argumentOpt) { var name = argumentOpt != null && argumentOpt.NameColon != null ? argumentOpt.NameColon.Name.Identifier.ValueText : null; return InferTypeInArgument(index, parameterizedSymbols, name); }
static string GetArgumentName(ArgumentSyntax argument) { return argument.NameColon != null ? argument.NameColon.Name.Identifier.ValueText : ""; }
public override void VisitArgument(ArgumentSyntax node) { base.VisitArgument(node); if (!node.RefOrOutKeyword.IsKind(SyntaxKind.None)) { CheckForFieldWrite(node.Expression); } }
private bool IsAccessed( SemanticModel semanticModel, ISymbol outSymbol, BlockSyntax enclosingBlockOfLocalStatement, LocalDeclarationStatementSyntax localStatement, ArgumentSyntax argumentNode, CancellationToken cancellationToken) { var localStatementStart = localStatement.Span.Start; var argumentNodeStart = argumentNode.Span.Start; var variableName = outSymbol.Name; // Walk the block that the local is declared in looking for accesses. // We can ignore anything prior to the actual local declaration point, // and we only need to check up until we reach the out-argument. foreach (var descendentNode in enclosingBlockOfLocalStatement.DescendantNodes()) { var descendentStart = descendentNode.Span.Start; if (descendentStart <= localStatementStart) { // This node is before the local declaration. Can ignore it entirely as it could // not be an access to the local. continue; } if (descendentStart >= argumentNodeStart) { // We reached the out-var. We can stop searching entirely. break; } if (descendentNode.IsKind(SyntaxKind.IdentifierName)) { // See if this looks like an accessor to the local variable syntactically. var identifierName = (IdentifierNameSyntax)descendentNode; if (identifierName.Identifier.ValueText == variableName) { // Confirm that it is a access of the local. var symbol = semanticModel.GetSymbolInfo(identifierName, cancellationToken).Symbol; if (outSymbol.Equals(symbol)) { // We definitely accessed the local before the out-argument. We // can't inline this local. return true; } } } } // No accesses detected return false; }
public override SyntaxNode VisitArgument(ArgumentSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var newArgument = (ArgumentSyntax)base.VisitArgument(node); var argumentType = _semanticModel.GetTypeInfo(node.Expression).ConvertedType; if (argumentType != null && !IsPassedToDelegateCreationExpression(node, argumentType)) { var specAnalyzer = new SpeculationAnalyzer(node.Expression, newArgument.Expression, _semanticModel, _cancellationToken); var speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel; var speculatedExpession = specAnalyzer.ReplacedExpression; bool wasCastAdded; var newArgumentExpression = speculatedExpession.CastIfPossible(argumentType, speculatedExpession.SpanStart, speculativeSemanticModel, out wasCastAdded); if (wasCastAdded) { return newArgument.WithExpression(newArgumentExpression); } } return newArgument; }
/// <summary> /// Given an argument node, tries to generate an appropriate name that can be used for that /// argument. /// </summary> public static string GenerateNameForArgument( this SemanticModel semanticModel, ArgumentSyntax argument) { // If it named argument then we use the name provided. if (argument.NameColon != null) { return argument.NameColon.Name.Identifier.ValueText; } return semanticModel.GenerateNameForExpression(argument.Expression); }
private bool TryGenerateArgument(ArgumentSyntax argument) { using (ArgumentTag()) { return TryGenerateExpression(argument.Expression); } }