public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action <Diagnostic> addDiagnostic, CancellationToken cancellationToken) { if (node.CSharpKind() == SyntaxKind.SimpleMemberAccessExpression) { var memberAccess = (MemberAccessExpressionSyntax)node; var methodSymbol = semanticModel.GetSymbolInfo(memberAccess.Name).Symbol as IMethodSymbol; if (methodSymbol != null && methodSymbol.MetadataName == Dispose) { var fieldSymbol = semanticModel.GetSymbolInfo(memberAccess.Expression).Symbol as IFieldSymbol; if (fieldSymbol != null) { NoteFieldDisposed(fieldSymbol); } } } else if (node.CSharpKind() == SyntaxKind.UsingStatement) { var usingStatementExpression = ((UsingStatementSyntax)node).Expression; if (usingStatementExpression != null) { var fieldSymbol = semanticModel.GetSymbolInfo(usingStatementExpression).Symbol as IFieldSymbol; if (fieldSymbol != null) { NoteFieldDisposed(fieldSymbol); } } } }
private SyntaxNode ComputeReplacement(SyntaxNode old1, SyntaxNode old2) { // old1 is the original node in the tree // old2 is the (potentially) modified version of old1 // that is, old1 is in dict_old_to_new but old2 wont be // if any of its chilrden have been modified if (dict_old_to_new.Keys.Contains(old1)) // this check is redundant? { switch (old2.CSharpKind()) { case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.AddAccessorDeclaration: // who knew this was a thing? maybe this will work case SyntaxKind.RemoveAccessorDeclaration: // who knew this was a thing? maybe this will work //Console.WriteLine("Replacing {0} with {1}", old2, dict_old_to_new[old2]); return(dict_old_to_new[old2]); default: RBLogger.Error("Unhandled syntax node kind {0}", old2.CSharpKind()); break; } } return(old2); // don't replace }
public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action <Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken) { var body = default(StatementSyntax); var token = default(SyntaxToken); switch (node.CSharpKind()) { case SyntaxKind.IfStatement: var ifStmt = (IfStatementSyntax)node; body = ifStmt.Statement; token = ifStmt.IfKeyword; break; case SyntaxKind.ElseClause: var elseStmt = (ElseClauseSyntax)node; body = elseStmt.Statement; token = elseStmt.ElseKeyword; break; case SyntaxKind.WhileStatement: var whileStmt = (WhileStatementSyntax)node; body = whileStmt.Statement; token = whileStmt.WhileKeyword; break; case SyntaxKind.ForStatement: var forStmt = (ForStatementSyntax)node; body = forStmt.Statement; token = forStmt.ForKeyword; break; case SyntaxKind.ForEachStatement: var forEachStmt = (ForEachStatementSyntax)node; body = forEachStmt.Statement; token = forEachStmt.ForEachKeyword; break; } if (!body.IsKind(SyntaxKind.Block)) { // // else if { ... } is fine. // if (node.IsKind(SyntaxKind.ElseClause) && body.IsKind(SyntaxKind.IfStatement)) { return; } var location = token.GetLocation(); var name = kindNames[node.CSharpKind()]; addDiagnostic(Diagnostic.Create(desc, location, name)); } }
/// <summary> /// Inspects the property values of the <paramref name="node"/> object using Reflection and /// creates API call descriptions for the property values recursively. Properties that are not /// essential to the shape of the syntax tree (such as Span) are ignored. /// </summary> private APIList QuotePropertyValues(SyntaxNode node) { var result = APIList.Create(); var properties = node.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); // Filter out non-essential properties listed in nonStructuralProperties result.Add(properties.Where(propertyInfo => !nonStructuralProperties.Contains(propertyInfo.Name)) .Select(propertyInfo => QuotePropertyValue(node, propertyInfo)) .Where(apiCall => apiCall != null).ToArray( )); // HACK: factory methods for the following node types accept back the first "kind" parameter // that we filter out above. Add an artificial "property value" that can be later used to // satisfy the first parameter of type SyntaxKind. if (node is AccessorDeclarationSyntax || node is BinaryExpressionSyntax || node is ClassOrStructConstraintSyntax || node is CheckedExpressionSyntax || node is CheckedStatementSyntax || node is ConstructorInitializerSyntax || node is GotoStatementSyntax || node is InitializerExpressionSyntax || node is LiteralExpressionSyntax || node is MemberAccessExpressionSyntax || node is OrderingSyntax || node is PostfixUnaryExpressionSyntax || node is PrefixUnaryExpressionSyntax || node is DocumentationCommentTriviaSyntax || node is SwitchLabelSyntax || node is YieldStatementSyntax) { result.Add(new ApiCall("Kind", "SyntaxKind." + node.CSharpKind( ).ToString( ))); } return(result); }
public override void Visit(SyntaxNode node) { // FIXME How comes a node can be null here? if (node != null) { if (supportedKinds.Contains(node.CSharpKind())) { currentBasicBlock.Statements.Add(node); } else if (node.IsKind(SyntaxKind.IfStatement)) { IfStatementSyntax ifNode = (IfStatementSyntax)node; ControlFlowBasicBlock conditionBasicBlock = currentBasicBlock; ControlFlowBasicBlock ifTrueBasicBlock = new ControlFlowBasicBlock(); ControlFlowBasicBlock afterIfBasicBlock = new ControlFlowBasicBlock(); conditionBasicBlock.Terminator = ifNode; Visit(ifNode.Condition); ifTrueBasicBlock.Successors.Add(afterIfBasicBlock); SetCurrentBasicBlock(ifTrueBasicBlock); Visit(ifNode.Statement); SetCurrentBasicBlock(afterIfBasicBlock); conditionBasicBlock.Successors.Add(ifTrueBasicBlock); conditionBasicBlock.Successors.Add(afterIfBasicBlock); } else { base.Visit(node); } } }
private SyntaxNode GetExpression(SyntaxNode node) { if (node.CSharpKind() == CSharp.SyntaxKind.Argument) { return(((CSharp.Syntax.ArgumentSyntax)node).Expression); } else if (node.CSharpKind() == CSharp.SyntaxKind.AttributeArgument) { return(((CSharp.Syntax.AttributeArgumentSyntax)node).Expression); } else if (node.VbKind() == VB.SyntaxKind.SimpleArgument) { return(((VB.Syntax.SimpleArgumentSyntax)node).Expression); } return(node); }
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken) { // if nothing can be fixed, return the unchanged node var newRoot = root; var kind = nodeToFix.CSharpKind(); var syntaxFactoryService = document.GetLanguageService<SyntaxGenerator>(); switch (kind) { case SyntaxKind.Argument: // StringComparison.CurrentCulture => StringComparison.Ordinal // StringComparison.CurrentCultureIgnoreCase => StringComparison.OrdinalIgnoreCase var argument = (ArgumentSyntax)nodeToFix; var memberAccess = argument.Expression as MemberAccessExpressionSyntax; if (memberAccess != null) { // preserve the "IgnoreCase" suffix if present bool isIgnoreCase = memberAccess.Name.GetText().ToString().EndsWith(CA1309DiagnosticAnalyzer.IgnoreCaseText); var newOrdinalText = isIgnoreCase ? CA1309DiagnosticAnalyzer.OrdinalIgnoreCaseText : CA1309DiagnosticAnalyzer.OrdinalText; var newIdentifier = syntaxFactoryService.IdentifierName(newOrdinalText); var newMemberAccess = memberAccess.WithName((SimpleNameSyntax)newIdentifier).WithAdditionalAnnotations(Formatter.Annotation); newRoot = root.ReplaceNode(memberAccess, newMemberAccess); } break; case SyntaxKind.IdentifierName: // string.Equals(a, b) => string.Equals(a, b, StringComparison.Ordinal) // string.Compare(a, b) => string.Compare(a, b, StringComparison.Ordinal) var identifier = (IdentifierNameSyntax)nodeToFix; var invokeParent = identifier.GetAncestor<InvocationExpressionSyntax>(); if (invokeParent != null) { var methodSymbol = model.GetSymbolInfo(identifier).Symbol as IMethodSymbol; if (methodSymbol != null && CanAddStringComparison(methodSymbol)) { // append a new StringComparison.Ordinal argument var newArg = syntaxFactoryService.Argument(CreateOrdinalMemberAccess(syntaxFactoryService, model)) .WithAdditionalAnnotations(Formatter.Annotation); var newInvoke = invokeParent.AddArgumentListArguments((ArgumentSyntax)newArg).WithAdditionalAnnotations(Formatter.Annotation); newRoot = root.ReplaceNode(invokeParent, newInvoke); } } break; case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: // "a == b" => "string.Equals(a, b, StringComparison.Ordinal)" // "a != b" => "!string.Equals(a, b, StringComparison.Ordinal)" var binaryExpression = (BinaryExpressionSyntax)nodeToFix; var invocation = CreateEqualsExpression(syntaxFactoryService, model, binaryExpression.Left, binaryExpression.Right, kind == SyntaxKind.EqualsExpression).WithAdditionalAnnotations(Formatter.Annotation); newRoot = root.ReplaceNode(nodeToFix, invocation); break; } if (newRoot == root) { return Task.FromResult(document); } return Task.FromResult(document.WithSyntaxRoot(newRoot)); }
private static bool IsStatement(this SyntaxNode node) { switch (node.CSharpKind()) { case SyntaxKind.LocalDeclarationStatement: case SyntaxKind.ExpressionStatement: case SyntaxKind.LabeledStatement: case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.UsingStatement: case SyntaxKind.FixedStatement: case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: case SyntaxKind.UnsafeStatement: case SyntaxKind.LockStatement: case SyntaxKind.IfStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.TryStatement: return(true); default: return(false); } }
public static CodeGenerationDestination GetDestination(SyntaxNode destination) { if (destination != null) { switch (destination.CSharpKind()) { case SyntaxKind.ClassDeclaration: return(CodeGenerationDestination.ClassType); case SyntaxKind.CompilationUnit: return(CodeGenerationDestination.CompilationUnit); case SyntaxKind.EnumDeclaration: return(CodeGenerationDestination.EnumType); case SyntaxKind.InterfaceDeclaration: return(CodeGenerationDestination.InterfaceType); case SyntaxKind.NamespaceDeclaration: return(CodeGenerationDestination.Namespace); case SyntaxKind.StructDeclaration: return(CodeGenerationDestination.StructType); default: return(CodeGenerationDestination.Unspecified); } } return(CodeGenerationDestination.Unspecified); }
public PathSyntaxReference(SyntaxNode node) { this.tree = node.SyntaxTree; this.kind = node.CSharpKind(); this.textSpan = node.Span; this.pathFromRoot = ComputePathFromRoot(node); }
private static bool IsContract(string contract_type, SyntaxNode node) { IEnumerable <ISymbol> symbols = GetContractMemberSymbols(Compilation, contract_type); if (node.CSharpKind() == SyntaxKind.ExpressionStatement) { var invoc = node.ChildNodes().First() as InvocationExpressionSyntax; if (invoc != null) { var memacc = invoc.Expression as MemberAccessExpressionSyntax; if (memacc != null && memacc.Name.ToString().Equals(contract_type)) { var si = SemanticModel.GetSymbolInfo(invoc); if (si.Symbol != null) { if (symbols.Where(x => si.Symbol.Equals(x)).Any()) { return(true); } } } } } return(false); }
private bool IsPropertyNameOfObjectInitializer(SimpleNameSyntax identifierName) { SyntaxNode currentNode = identifierName; SyntaxNode parent = identifierName; while (parent != null) { if (parent.CSharpKind() == SyntaxKind.ObjectInitializerExpression) { return(currentNode.CSharpKind() == SyntaxKind.SimpleAssignmentExpression && object.Equals(((AssignmentExpressionSyntax)currentNode).Left, identifierName)); } else if (parent is ExpressionSyntax) { currentNode = parent; parent = parent.Parent; continue; } else { return(false); } } return(false); }
internal override Task <Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var charSetType = WellKnownTypes.CharSet(model.Compilation); var dllImportType = WellKnownTypes.DllImportAttribute(model.Compilation); var marshalAsType = WellKnownTypes.MarshalAsAttribute(model.Compilation); var unmanagedType = WellKnownTypes.UnmanagedType(model.Compilation); if (charSetType == null || dllImportType == null || marshalAsType == null || unmanagedType == null) { return(Task.FromResult(document)); } var syntaxFactoryService = document.Project.LanguageServices.GetService <SyntaxGenerator>(); // return the unchanged root if no fix is available var newRoot = root; if (nodeToFix.CSharpKind() == SyntaxKind.Attribute) { // could be either a [DllImport] or [MarshalAs] attribute var attribute = (AttributeSyntax)nodeToFix; var attributeType = model.GetSymbolInfo(attribute).Symbol; var arguments = attribute.ArgumentList.Arguments; if (dllImportType.Equals(attributeType.ContainingType)) { // [DllImport] attribute, add or replace CharSet named parameter var argumentValue = CreateCharSetArgument(syntaxFactoryService, charSetType).WithAdditionalAnnotations(Formatter.Annotation); var namedParameter = arguments.FirstOrDefault(arg => arg.NameEquals != null && arg.NameEquals.Name.Identifier.Text == CharSetText); if (namedParameter == null) { // add the parameter namedParameter = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals(CharSetText), null, (ExpressionSyntax)argumentValue) .WithAdditionalAnnotations(Formatter.Annotation); var newArguments = arguments.Add(namedParameter); var newArgumentList = attribute.ArgumentList.WithArguments(newArguments); newRoot = root.ReplaceNode(attribute.ArgumentList, newArgumentList); } else { // replace the parameter var newNamedParameter = namedParameter.WithExpression((ExpressionSyntax)argumentValue); newRoot = root.ReplaceNode(namedParameter, newNamedParameter); } } else if (marshalAsType.Equals(attributeType.ContainingType) && arguments.Count == 1) { // [MarshalAs] attribute, replace the only argument var newExpression = CreateMarshalAsArgument(syntaxFactoryService, unmanagedType) .WithLeadingTrivia(arguments[0].GetLeadingTrivia()) .WithTrailingTrivia(arguments[0].GetTrailingTrivia()); var newArgument = arguments[0].WithExpression((ExpressionSyntax)newExpression); newRoot = root.ReplaceNode(arguments[0], newArgument); } } return(Task.FromResult(document.WithSyntaxRoot(newRoot))); }
public PositionalSyntaxReference(SyntaxNode node) { this.tree = node.SyntaxTree; this.textSpan = node.Span; this.kind = node.CSharpKind(); System.Diagnostics.Debug.Assert(textSpan.Length > 0); }
public override void Visit(SyntaxNode node) { Indent++; var indents = new String(' ', Indent * 2); Console.WriteLine(indents + node.CSharpKind()); base.Visit(node); Indent--; }
public static bool IsAnonymousMethodBlock(this SyntaxNode node) { if (node.CSharpKind() != SyntaxKind.Block) { return(false); } return(node.Parent.CSharpKind() == SyntaxKind.AnonymousMethodExpression); }
public static bool MatchesKind(this SyntaxNode node, params SyntaxKind[] kinds) { if (node == null) { return(false); } return(kinds.Contains(node.CSharpKind())); }
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var charSetType = WellKnownTypes.CharSet(model.Compilation); var dllImportType = WellKnownTypes.DllImportAttribute(model.Compilation); var marshalAsType = WellKnownTypes.MarshalAsAttribute(model.Compilation); var unmanagedType = WellKnownTypes.UnmanagedType(model.Compilation); if (charSetType == null || dllImportType == null || marshalAsType == null || unmanagedType == null) { return Task.FromResult(document); } var syntaxFactoryService = document.Project.LanguageServices.GetService<SyntaxGenerator>(); // return the unchanged root if no fix is available var newRoot = root; if (nodeToFix.CSharpKind() == SyntaxKind.Attribute) { // could be either a [DllImport] or [MarshalAs] attribute var attribute = (AttributeSyntax)nodeToFix; var attributeType = model.GetSymbolInfo(attribute).Symbol; var arguments = attribute.ArgumentList.Arguments; if (dllImportType.Equals(attributeType.ContainingType)) { // [DllImport] attribute, add or replace CharSet named parameter var argumentValue = CreateCharSetArgument(syntaxFactoryService, charSetType).WithAdditionalAnnotations(Formatter.Annotation); var namedParameter = arguments.FirstOrDefault(arg => arg.NameEquals != null && arg.NameEquals.Name.Identifier.Text == CharSetText); if (namedParameter == null) { // add the parameter namedParameter = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals(CharSetText), null, (ExpressionSyntax)argumentValue) .WithAdditionalAnnotations(Formatter.Annotation); var newArguments = arguments.Add(namedParameter); var newArgumentList = attribute.ArgumentList.WithArguments(newArguments); newRoot = root.ReplaceNode(attribute.ArgumentList, newArgumentList); } else { // replace the parameter var newNamedParameter = namedParameter.WithExpression((ExpressionSyntax)argumentValue); newRoot = root.ReplaceNode(namedParameter, newNamedParameter); } } else if (marshalAsType.Equals(attributeType.ContainingType) && arguments.Count == 1) { // [MarshalAs] attribute, replace the only argument var newExpression = CreateMarshalAsArgument(syntaxFactoryService, unmanagedType) .WithLeadingTrivia(arguments[0].GetLeadingTrivia()) .WithTrailingTrivia(arguments[0].GetTrailingTrivia()); var newArgument = arguments[0].WithExpression((ExpressionSyntax)newExpression); newRoot = root.ReplaceNode(arguments[0], newArgument); } } return Task.FromResult(document.WithSyntaxRoot(newRoot)); }
public static SyntaxTokenList GetModifiers(this SyntaxNode member) { if (member != null) { switch (member.CSharpKind()) { case SyntaxKind.EnumDeclaration: return(((EnumDeclarationSyntax)member).Modifiers); case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: return(((TypeDeclarationSyntax)member).Modifiers); case SyntaxKind.DelegateDeclaration: return(((DelegateDeclarationSyntax)member).Modifiers); case SyntaxKind.FieldDeclaration: return(((FieldDeclarationSyntax)member).Modifiers); case SyntaxKind.EventFieldDeclaration: return(((EventFieldDeclarationSyntax)member).Modifiers); case SyntaxKind.ConstructorDeclaration: return(((ConstructorDeclarationSyntax)member).Modifiers); case SyntaxKind.DestructorDeclaration: return(((DestructorDeclarationSyntax)member).Modifiers); case SyntaxKind.PropertyDeclaration: return(((PropertyDeclarationSyntax)member).Modifiers); case SyntaxKind.EventDeclaration: return(((EventDeclarationSyntax)member).Modifiers); case SyntaxKind.IndexerDeclaration: return(((IndexerDeclarationSyntax)member).Modifiers); case SyntaxKind.OperatorDeclaration: return(((OperatorDeclarationSyntax)member).Modifiers); case SyntaxKind.ConversionOperatorDeclaration: return(((ConversionOperatorDeclarationSyntax)member).Modifiers); case SyntaxKind.MethodDeclaration: return(((MethodDeclarationSyntax)member).Modifiers); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return(((AccessorDeclarationSyntax)member).Modifiers); } } return(default(SyntaxTokenList)); }
public static bool IsLambdaBodyBlock(this SyntaxNode node) { if (node.CSharpKind() != SyntaxKind.Block) { return(false); } return(node.Parent.CSharpKind() == SyntaxKind.SimpleLambdaExpression || node.Parent.CSharpKind() == SyntaxKind.ParenthesizedLambdaExpression); }
internal static string GetLocalName(SyntaxNode node) { switch (node.CSharpKind()) { case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)node).Identifier.ToString(); default: throw new NotImplementedException(); } }
public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) { if (node == null) { return(false); } var csharpKind = node.CSharpKind(); return(csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5); }
internal static string GetLocalName(SyntaxNode node) { switch (node.CSharpKind()) { case SyntaxKind.VariableDeclarator: return(((VariableDeclaratorSyntax)node).Identifier.ToString()); default: throw new NotImplementedException(); } }
private bool IsControlBlock(SyntaxNode node) { var parent = node != null ? node.Parent : null; return((node != null && node.CSharpKind() == SyntaxKind.SwitchStatement) || (parent != null && (parent.CSharpKind() == SyntaxKind.IfStatement || parent.CSharpKind() == SyntaxKind.ElseClause || parent.CSharpKind() == SyntaxKind.WhileStatement || parent.CSharpKind() == SyntaxKind.DoStatement || parent.CSharpKind() == SyntaxKind.ForEachStatement || parent.CSharpKind() == SyntaxKind.UsingStatement || parent.CSharpKind() == SyntaxKind.ForStatement || parent.CSharpKind() == SyntaxKind.TryStatement || parent.CSharpKind() == SyntaxKind.CatchClause || parent.CSharpKind() == SyntaxKind.FinallyClause))); }
public static bool IsContinuableConstruct(this SyntaxNode node) { switch (node.CSharpKind()) { case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: return(true); } return(false); }
public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action <Diagnostic> addDiagnostic, CancellationToken cancellationToken) { var kind = node.CSharpKind(); if (kind == SyntaxKind.InvocationExpression) { AnalyzeInvocationExpression((InvocationExpressionSyntax)node, semanticModel, addDiagnostic); } else if (kind == SyntaxKind.EqualsExpression || kind == SyntaxKind.NotEqualsExpression) { AnalyzeBinaryExpression((BinaryExpressionSyntax)node, semanticModel, addDiagnostic); } }
private void WriteJsonRecursive(JsonWriter writer, SyntaxNode node) { writer.WriteStartObject(); writer.WritePropertyName("kind"); writer.WriteValue(node.CSharpKind().ToString()); writer.WritePropertyName("nodes"); writer.WriteStartArray(); foreach (var child in node.ChildNodes()) { WriteJsonRecursive(writer, child); } writer.WriteEndArray(); writer.WriteEndObject(); }
private Node AsNode(SyntaxNode node, string text) { var ret = new Node(); ret.ChildNodes = new List <Node>(); ret.Kind = node.CSharpKind().ToString(); ret.Location = new QuickFix(); ret.Location.Text = text; ret.Location.Line = 1 + node.GetLocation().GetLineSpan().StartLinePosition.Line; ret.Location.Column = 1 + node.GetLocation().GetLineSpan().StartLinePosition.Character; ret.Location.EndLine = 1 + node.GetLocation().GetLineSpan().EndLinePosition.Line; ret.Location.EndColumn = 1 + node.GetLocation().GetLineSpan().EndLinePosition.Character; return(ret); }
private static SyntaxNode RemoveAllMembers(SyntaxNode declaration) { switch (declaration.CSharpKind()) { case SyntaxKind.CompilationUnit: return(((CompilationUnitSyntax)declaration).WithMembers(default(SyntaxList <MemberDeclarationSyntax>))); case SyntaxKind.NamespaceDeclaration: return(((PackageDeclarationSyntax)declaration).WithMembers(default(SyntaxList <MemberDeclarationSyntax>))); default: return(declaration); } }
protected override Location GetDiagnosticLocation(SyntaxNode node) { switch (node.CSharpKind()) { case SyntaxKind.MethodDeclaration: return(((MethodDeclarationSyntax)node).Identifier.GetLocation()); case SyntaxKind.Block: return(GetDiagnosticLocation(node.Parent)); default: return(Location.None); } }
private bool ShouldAnalyzeExpression(SyntaxNode expression, SemanticModel semanticModel) { switch (expression.CSharpKind()) { case SyntaxKind.ArrayCreationExpression: case SyntaxKind.ImplicitArrayCreationExpression: return(ShouldAnalyzeArrayCreationExpression(expression, semanticModel)); case SyntaxKind.SimpleMemberAccessExpression: return(true); default: return(false); } }
public static string GetKind(this SyntaxNode node) { var kind = string.Empty; if (node.Language == LanguageNames.CSharp) { kind = node.CSharpKind().ToString(); } else { kind = node.VBKind().ToString(); } return(kind); }
public static string GetKind(this SyntaxNode node) { var kind = string.Empty; if (node.Language == LanguageNames.CSharp) { kind = node.CSharpKind().ToString(); } //else //{ // kind = node.VisualBasicKind().ToString(); //} return(kind); }
public static bool IsAttributeName(SyntaxNode node) { var parent = node.Parent; if (parent == null || !IsName(node.CSharpKind())) { return false; } switch (parent.CSharpKind()) { case SyntaxKind.QualifiedName: var qn = (QualifiedNameSyntax)parent; return qn.Right == node ? IsAttributeName(parent) : false; case SyntaxKind.AliasQualifiedName: var an = (AliasQualifiedNameSyntax)parent; return an.Name == node ? IsAttributeName(parent) : false; } var p = node.Parent as AttributeSyntax; return p != null && p.Name == node; }
public bool TryGetSpeculativeSemanticModel(SemanticModel oldSemanticModel, SyntaxNode oldNode, SyntaxNode newNode, out SemanticModel speculativeModel) { Contract.Requires(oldNode.CSharpKind() == newNode.CSharpKind()); var model = oldSemanticModel; // currently we only support method. field support will be added later. var oldMethod = oldNode as BaseMethodDeclarationSyntax; var newMethod = newNode as BaseMethodDeclarationSyntax; if (oldMethod == null || newMethod == null || oldMethod.Body == null) { speculativeModel = null; return false; } SemanticModel csharpModel; bool success = model.TryGetSpeculativeSemanticModelForMethodBody(oldMethod.Body.OpenBraceToken.Span.End, newMethod, out csharpModel); speculativeModel = csharpModel; return success; }
public override void DefaultVisit(SyntaxNode node) { SyntaxKind nodeKind = node.CSharpKind(); bool diagnose = ((SyntaxTree)node.SyntaxTree).ReportDocumentationCommentDiagnostics(); if (nodeKind == SyntaxKind.XmlCrefAttribute) { XmlCrefAttributeSyntax crefAttr = (XmlCrefAttributeSyntax)node; CrefSyntax cref = crefAttr.Cref; BinderFactory factory = compilation.GetBinderFactory(cref.SyntaxTree); Binder binder = factory.GetBinder(cref); // Do this for the diagnostics, even if it won't be written. DiagnosticBag crefDiagnostics = DiagnosticBag.GetInstance(); string docCommentId = GetDocumentationCommentId(cref, binder, crefDiagnostics); if (diagnose) { diagnostics.AddRange(crefDiagnostics); } crefDiagnostics.Free(); if ((object)writer != null) { Visit(crefAttr.Name); VisitToken(crefAttr.EqualsToken); // Not going to visit normally, because we want to skip trivia within // the attribute value. crefAttr.StartQuoteToken.WriteTo(writer, leading: true, trailing: false); // We're not going to visit the cref because we want to bind it // and write a doc comment ID in its place. writer.Write(docCommentId); // Not going to visit normally, because we want to skip trivia within // the attribute value. crefAttr.EndQuoteToken.WriteTo(writer, leading: false, trailing: true); } // Don't descend - we've already written out everything necessary. return; } else if (nodeKind == SyntaxKind.XmlNameAttribute && diagnose) { XmlNameAttributeSyntax nameAttr = (XmlNameAttributeSyntax)node; BinderFactory factory = compilation.GetBinderFactory(nameAttr.SyntaxTree); Binder binder = factory.GetBinder(nameAttr, nameAttr.Identifier.SpanStart); // Do this for diagnostics, even if we aren't writing. DocumentationCommentCompiler.BindName(nameAttr, binder, memberSymbol, ref documentedParameters, ref documentedTypeParameters, diagnostics); // Do descend - we still need to write out the tokens of the attribute. } // NOTE: if we're recording any include element nodes (i.e. if includeElementsNodes is non-null), // then we want to record all of them, because we won't be able to distinguish in the XML DOM. if ((object)includeElementNodes != null) { XmlNameSyntax nameSyntax = null; if (nodeKind == SyntaxKind.XmlEmptyElement) { nameSyntax = ((XmlEmptyElementSyntax)node).Name; } else if (nodeKind == SyntaxKind.XmlElementStartTag) { nameSyntax = ((XmlElementStartTagSyntax)node).Name; } if ((object)nameSyntax != null && (object)nameSyntax.Prefix == null && DocumentationCommentXmlNames.ElementEquals(nameSyntax.LocalName.ValueText, DocumentationCommentXmlNames.IncludeElementName)) { includeElementNodes.Add((CSharpSyntaxNode)node); } } base.DefaultVisit(node); }
public bool IsElementAccessExpression(SyntaxNode node) { return node.CSharpKind() == SyntaxKind.ElementAccessExpression; }
public bool IsIndexerMemberCRef(SyntaxNode node) { return node.CSharpKind() == SyntaxKind.IndexerMemberCref; }