protected override bool TryInitializeState( Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken, out INamedTypeSymbol classType, out INamedTypeSymbol abstractClassType) { var baseClassNode = node as TypeSyntax; if (baseClassNode != null && baseClassNode.Parent is BaseTypeSyntax && baseClassNode.Parent.IsParentKind(SyntaxKind.BaseList) && ((BaseTypeSyntax)baseClassNode.Parent).Type == baseClassNode) { if (baseClassNode.Parent.Parent.IsParentKind(SyntaxKind.ClassDeclaration)) { abstractClassType = model.GetTypeInfo(baseClassNode, cancellationToken).Type as INamedTypeSymbol; cancellationToken.ThrowIfCancellationRequested(); if (abstractClassType.IsAbstractClass()) { var classDecl = baseClassNode.Parent.Parent.Parent as ClassDeclarationSyntax; classType = model.GetDeclaredSymbol(classDecl, cancellationToken) as INamedTypeSymbol; return classType != null && abstractClassType != null; } } } classType = null; abstractClassType = null; return false; }
private static async Task<Document> MakeMock(Document document, SyntaxNode invokationSyntax, CancellationToken cancellationToken) { var testSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var testInitMethodDecl = TestSemanticHelper.GetTestInitializeMethod(testSemanticModel); var declaredFields = testInitMethodDecl.Parent.ChildNodes().OfType<FieldDeclarationSyntax>().ToArray(); var suts = testInitMethodDecl.GetSuts(testSemanticModel, declaredFields); var memberAccessExpressions = invokationSyntax.DescendantNodes() .OfType<ExpressionSyntax>() .Where(x => x is InvocationExpressionSyntax || x is MemberAccessExpressionSyntax) .Select(expr => { var memberAccess = expr as MemberAccessExpressionSyntax; var invokationExpression = expr as InvocationExpressionSyntax; var expression = invokationExpression == null ? memberAccess : invokationExpression.Expression; return expression; }); var invokedMethodsOfMocks = memberAccessExpressions.SelectMany(expressionSyntax => MocksAnalyzingEngine.GetInvokedMethodsOfMock(expressionSyntax, testSemanticModel, suts)) .DistinctBy(x => string.Join(",", x.FieldsToSetup.SelectMany(y => y.Field.Select(z => z))) + "," + x.MethodOrPropertySymbol) .ToArray(); if (invokedMethodsOfMocks.Length == 0) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); ChangesMaker.ApplyChanges(invokationSyntax, editor, invokedMethodsOfMocks); return editor.GetChangedDocument(); }
private static Solution UpdateMainDocument(Document document, SyntaxNode root, MethodDeclarationSyntax method, IEnumerable<IGrouping<Document, ReferenceLocation>> documentGroups) { var mainDocGroup = documentGroups.FirstOrDefault(dg => dg.Key.Equals(document)); SyntaxNode newRoot; if (mainDocGroup == null) { newRoot = root.ReplaceNode(method, method.AddModifiers(staticToken)); } else { var diagnosticNodes = mainDocGroup.Select(referenceLocation => root.FindNode(referenceLocation.Location.SourceSpan)).ToList(); newRoot = root.TrackNodes(diagnosticNodes.Union(new[] { method })); newRoot = newRoot.ReplaceNode(newRoot.GetCurrentNode(method), method.AddModifiers(staticToken)); foreach (var diagnosticNode in diagnosticNodes) { var token = newRoot.FindToken(diagnosticNode.GetLocation().SourceSpan.Start); var tokenParent = token.Parent; if (token.Parent.IsKind(SyntaxKind.IdentifierName)) continue; var invocationExpression = newRoot.GetCurrentNode(diagnosticNode).FirstAncestorOrSelfOfType<InvocationExpressionSyntax>()?.Expression; if (invocationExpression == null || invocationExpression.IsKind(SyntaxKind.IdentifierName)) continue; var memberAccess = invocationExpression as MemberAccessExpressionSyntax; if (memberAccess == null) continue; var newMemberAccessParent = memberAccess.Parent.ReplaceNode(memberAccess, memberAccess.Name) .WithAdditionalAnnotations(Formatter.Annotation); newRoot = newRoot.ReplaceNode(memberAccess.Parent, newMemberAccessParent); } } var newSolution = document.Project.Solution.WithDocumentSyntaxRoot(document.Id, newRoot); return newSolution; }
private SyntaxNode ReplaceTokens( SyntaxNode root, IEnumerable<SyntaxToken> oldTokens, Func<SyntaxToken, SyntaxToken, SyntaxToken> computeReplacementToken) { return root.ReplaceTokens(oldTokens, (o, n) => computeReplacementToken(o, n)); }
private ITriviaSavedResult CreateResult( SyntaxNode root, Dictionary<TriviaLocation, SyntaxAnnotation> annotations, Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> triviaList) { return new Result(root, _endOfLineKind, annotations, triviaList); }
public SyntaxTree UnWeave(SyntaxNode y) { var dcs = y as MethodDeclarationSyntax; if (dcs != null) return this.UnWeave(dcs); var cds = y as ClassDeclarationSyntax; return (cds != null) ? this.UnWeave(cds) : null; }
/// <summary> /// This is jus a test to check the ability to preprocess the AST /// </summary> /// <param name="methodNode"></param> /// <param name="semanticModel"></param> /// <returns></returns> public static IMethodSymbol SimplifyASTForMethod(ref SyntaxNode methodNode, ref SemanticModel semanticModel) { var oldMethod = semanticModel.GetDeclaredSymbol(methodNode) as IMethodSymbol; var newMethodNode = MethodSimpifier.Test(methodNode); var annotation = new SyntaxAnnotation("Hi"); newMethodNode = newMethodNode.WithAdditionalAnnotations(annotation); var root = methodNode.SyntaxTree.GetRoot(); var newRoot = root.ReplaceNode(methodNode, newMethodNode); var oldCompilation = semanticModel.Compilation; var newCompilation = oldCompilation.ReplaceSyntaxTree(root.SyntaxTree, newRoot.SyntaxTree); var newSemanticModel = newCompilation.GetSemanticModel(newRoot.SyntaxTree); var recoveredMethodNode = newRoot.GetAnnotatedNodes(annotation).Single(); var method = newSemanticModel.GetDeclaredSymbol(recoveredMethodNode) as IMethodSymbol; methodNode = recoveredMethodNode; semanticModel = newSemanticModel; return method; }
public async static Task<Solution> MakeAutoPropertyAsync(Document document, SyntaxNode root, PropertyDeclarationSyntax property, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken); var getterReturn = (ReturnStatementSyntax)property.AccessorList.Accessors.First(a => a.Keyword.ValueText == "get").Body.Statements.First(); var returnIdentifier = (IdentifierNameSyntax)(getterReturn.Expression is MemberAccessExpressionSyntax ? ((MemberAccessExpressionSyntax)getterReturn.Expression).Name : getterReturn.Expression); var returnIdentifierSymbol = semanticModel.GetSymbolInfo(returnIdentifier).Symbol; var variableDeclarator = (VariableDeclaratorSyntax)returnIdentifierSymbol.DeclaringSyntaxReferences.First().GetSyntax(); var fieldDeclaration = variableDeclarator.FirstAncestorOfType<FieldDeclarationSyntax>(); root = root.TrackNodes(returnIdentifier, fieldDeclaration, property); document = document.WithSyntaxRoot(root); root = await document.GetSyntaxRootAsync(cancellationToken); semanticModel = await document.GetSemanticModelAsync(cancellationToken); returnIdentifier = root.GetCurrentNode(returnIdentifier); returnIdentifierSymbol = semanticModel.GetSymbolInfo(returnIdentifier).Symbol; var newProperty = GetSimpleProperty(property, variableDeclarator) .WithTriviaFrom(property) .WithAdditionalAnnotations(Formatter.Annotation); var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, returnIdentifierSymbol, property.Identifier.ValueText, document.Project.Solution.Workspace.Options, cancellationToken); document = newSolution.GetDocument(document.Id); root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); root = root.InsertNodesAfter(root.GetCurrentNode(property), new[] { newProperty }); var multipleVariableDeclaration = fieldDeclaration.Declaration.Variables.Count > 1; if (multipleVariableDeclaration) { var newfieldDeclaration = fieldDeclaration.WithDeclaration(fieldDeclaration.Declaration.RemoveNode(variableDeclarator, SyntaxRemoveOptions.KeepNoTrivia)); root = root.RemoveNode(root.GetCurrentNode<SyntaxNode>(property), SyntaxRemoveOptions.KeepNoTrivia); root = root.ReplaceNode(root.GetCurrentNode(fieldDeclaration), newfieldDeclaration); } else { root = root.RemoveNodes(root.GetCurrentNodes<SyntaxNode>(new SyntaxNode[] { fieldDeclaration, property }), SyntaxRemoveOptions.KeepNoTrivia); } document = document.WithSyntaxRoot(root); return document.Project.Solution; }
private Task<Solution> UseExpressionBodiedMemberAsync(Document document, SyntaxNode root, SyntaxNode statement) { var returnStatement = (ReturnStatementSyntax) statement; var expression = returnStatement.Expression; var arrowClause = SyntaxFactory.ArrowExpressionClause(expression); var property = statement.AncestorsAndSelf().OfType<PropertyDeclarationSyntax>().FirstOrDefault(); if (property != null) { var newProperty = property.RemoveNode(property.AccessorList, SyntaxRemoveOptions.KeepNoTrivia) .WithExpressionBody(arrowClause) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); root = root.ReplaceNode(property, newProperty); } var method = statement.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().FirstOrDefault(); if (method != null) { root = root.ReplaceNode(method, method.RemoveNode(method.Body, SyntaxRemoveOptions.KeepNoTrivia) .WithExpressionBody(arrowClause) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))); } return Task.FromResult(document.WithSyntaxRoot(root).Project.Solution); }
private bool CompareAttributes( AttributeSyntax oldAttribute, AttributeSyntax newAttribute, SyntaxNode newNodeParent, CodeModelEventQueue eventQueue) { Debug.Assert(oldAttribute != null && newAttribute != null); bool same = true; if (!CompareNames(oldAttribute.Name, newAttribute.Name)) { EnqueueChangeEvent(newAttribute, newNodeParent, CodeModelEventType.Rename, eventQueue); same = false; } // If arguments have changed enqueue a element changed (arguments changed) node if (!CompareAttributeArguments(oldAttribute.ArgumentList, newAttribute.ArgumentList)) { EnqueueChangeEvent(newAttribute, newNodeParent, CodeModelEventType.ArgChange, eventQueue); same = false; } return same; }
private static bool IsNameableNode(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.EnumMemberDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.StructDeclaration: return true; case SyntaxKind.VariableDeclarator: // Could be a regular field or an event field. return node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>() != null; default: return false; } }
private static IEnumerable<SyntaxToken> GetAsyncOrAwaitTokens(SyntaxNode node) { return from token in node.DescendantTokens() where token.IsKind(SyntaxKind.IdentifierToken) && AsyncOrAwait.Contains(token.ToString()) select token; }
private IReadOnlyList<MemberDeclarationSyntax> GetValidMembers(SyntaxNode node) { return CSharpCodeModelService .GetChildMemberNodes(node) .Where(n => !n.IsKind(SyntaxKind.IncompleteMember)) .ToArray(); }
SyntaxNode AddNewModifier(SyntaxNode node) { SyntaxToken newToken = SyntaxFactory.Token(SyntaxKind.NewKeyword); switch (node.Kind()) { //couldn't find a common base case SyntaxKind.IndexerDeclaration: var indexer = (IndexerDeclarationSyntax)node; return indexer.AddModifiers(newToken); case SyntaxKind.ClassDeclaration: var classDecl = (ClassDeclarationSyntax)node; return classDecl.AddModifiers(newToken); case SyntaxKind.PropertyDeclaration: var propDecl = (PropertyDeclarationSyntax)node; return propDecl.AddModifiers(newToken); case SyntaxKind.MethodDeclaration: var methDecl = (MethodDeclarationSyntax)node; return methDecl.AddModifiers(newToken); case SyntaxKind.StructDeclaration: var structDecl = (StructDeclarationSyntax)node; return structDecl.AddModifiers(newToken); case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; return enumDecl.AddModifiers(newToken); case SyntaxKind.InterfaceDeclaration: var intDecl = (InterfaceDeclarationSyntax)node; return intDecl.AddModifiers(newToken); case SyntaxKind.DelegateDeclaration: var deleDecl = (DelegateDeclarationSyntax)node; return deleDecl.AddModifiers(newToken); default: return node; } }
private static ISymbol GetDeclaredSymbol(SemanticModel model, SyntaxNode node, bool getSymbol, CancellationToken cancellationToken) { if (!getSymbol) { return null; } var declaredSymbol = model.GetDeclaredSymbol(node, cancellationToken); // For namespace declarations, GetDeclaredSymbol returns a compilation scoped namespace symbol, // which includes declarations across the compilation, including those in referenced assemblies. // However, we are only interested in the namespace symbol scoped to the compilation's source assembly. var namespaceSymbol = declaredSymbol as INamespaceSymbol; if (namespaceSymbol != null && namespaceSymbol.ConstituentNamespaces.Length > 1) { var assemblyToScope = model.Compilation.Assembly; var assemblyScopedNamespaceSymbol = namespaceSymbol.ConstituentNamespaces.FirstOrDefault(ns => ns.ContainingAssembly == assemblyToScope); if (assemblyScopedNamespaceSymbol != null) { Debug.Assert(assemblyScopedNamespaceSymbol.ConstituentNamespaces.Length == 1); declaredSymbol = assemblyScopedNamespaceSymbol; } } return declaredSymbol; }
public static async Task<InsertionPoint> CreateAsync(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var root = document.Root; var annotation = new SyntaxAnnotation(); var newRoot = root.AddAnnotations(SpecializedCollections.SingletonEnumerable(Tuple.Create(node, annotation))); return new InsertionPoint(await document.WithSyntaxRootAsync(newRoot, cancellationToken).ConfigureAwait(false), annotation); }
private Document CreateCodeFix(Document document, Diagnostic diagnostic, SyntaxNode syntaxRoot) { SyntaxNode newSyntaxRoot = syntaxRoot; var node = syntaxRoot.FindNode(diagnostic.Location.SourceSpan); var indentationOptions = IndentationOptions.FromDocument(document); switch (node.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.EnumDeclaration: newSyntaxRoot = this.RegisterBaseTypeDeclarationCodeFix(syntaxRoot, (BaseTypeDeclarationSyntax)node, indentationOptions); break; case SyntaxKind.AccessorList: newSyntaxRoot = this.RegisterPropertyLikeDeclarationCodeFix(syntaxRoot, (BasePropertyDeclarationSyntax)node.Parent, indentationOptions); break; case SyntaxKind.Block: newSyntaxRoot = this.RegisterMethodLikeDeclarationCodeFix(syntaxRoot, (BaseMethodDeclarationSyntax)node.Parent, indentationOptions); break; case SyntaxKind.NamespaceDeclaration: newSyntaxRoot = this.RegisterNamespaceDeclarationCodeFix(syntaxRoot, (NamespaceDeclarationSyntax)node, indentationOptions); break; } return document.WithSyntaxRoot(newSyntaxRoot); }
private async Task<Document> ImplementOperatorEquals(Document document, SyntaxNode declaration, INamedTypeSymbol typeSymbol, CancellationToken cancellationToken) { DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var generator = editor.Generator; if (!typeSymbol.IsOperatorImplemented(WellKnownMemberNames.EqualityOperatorName)) { var equalityOperator = GenerateOperatorDeclaration(generator.TypeExpression(SpecialType.System_Boolean), WellKnownMemberNames.EqualityOperatorName, new[] { generator.ParameterDeclaration("left", generator.TypeExpression(typeSymbol)), generator.ParameterDeclaration("right", generator.TypeExpression(typeSymbol)), }, generator.ThrowStatement(generator.ObjectCreationExpression(generator.DottedName("System.NotImplementedException")))); editor.AddMember(declaration, equalityOperator); } if (!typeSymbol.IsOperatorImplemented(WellKnownMemberNames.InequalityOperatorName)) { var inequalityOperator = GenerateOperatorDeclaration(generator.TypeExpression(SpecialType.System_Boolean), WellKnownMemberNames.InequalityOperatorName, new[] { generator.ParameterDeclaration("left", generator.TypeExpression(typeSymbol)), generator.ParameterDeclaration("right", generator.TypeExpression(typeSymbol)), }, generator.ThrowStatement(generator.ObjectCreationExpression(generator.DottedName("System.NotImplementedException")))); editor.AddMember(declaration, inequalityOperator); } return editor.GetChangedDocument(); }
private void TestAnnotations( string expectedText, IList<TextSpan> expectedSpans, SyntaxNode fixedRoot, string annotationKind, bool compareTokens, ParseOptions parseOptions = null) { expectedSpans = expectedSpans ?? new List<TextSpan>(); var annotatedTokens = fixedRoot.GetAnnotatedNodesAndTokens(annotationKind).Select(n => (SyntaxToken)n).ToList(); Assert.Equal(expectedSpans.Count, annotatedTokens.Count); if (expectedSpans.Count > 0) { var expectedTokens = TokenUtilities.GetTokens(TokenUtilities.GetSyntaxRoot(expectedText, GetLanguage(), parseOptions)); var actualTokens = TokenUtilities.GetTokens(fixedRoot); for (var i = 0; i < Math.Min(expectedTokens.Count, actualTokens.Count); i++) { var expectedToken = expectedTokens[i]; var actualToken = actualTokens[i]; var actualIsConflict = annotatedTokens.Contains(actualToken); var expectedIsConflict = expectedSpans.Contains(expectedToken.Span); Assert.Equal(expectedIsConflict, actualIsConflict); } } }
protected override EvaluationResult EvaluateImpl(SyntaxNode node) { var declarationSyntax = (TypeDeclarationSyntax)node; var addAssignments = declarationSyntax .DescendantNodes() .Where(x => x.Kind() == SyntaxKind.AddAssignmentExpression) .Cast<AssignmentExpressionSyntax>() .AsArray(); var subtractAssignments = declarationSyntax.DescendantNodes() .Where(x => x.Kind() == SyntaxKind.SubtractAssignmentExpression) .Cast<AssignmentExpressionSyntax>() .AsArray(); var assignmentExpressionSyntaxes = addAssignments.DistinctBy(x => x.ToFullString()).AsArray(); if (assignmentExpressionSyntaxes.Count() != subtractAssignments.DistinctBy(x => x.ToFullString()).Count()) { var unmatched = assignmentExpressionSyntaxes.Where(x => !MatchingAssignmentExpressionExists(x, subtractAssignments)); var snippet = string.Join(Environment.NewLine, unmatched.Select(x => x.ToFullString())); return new EvaluationResult { Snippet = snippet }; } return null; }
private static async Task<Document> ChangeToThenByAsync(Document document, SyntaxNode syntaxNode, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken); var newRoot = root.ReplaceNode(syntaxNode, SyntaxFactory.IdentifierName("ThenBy")); return document.WithSyntaxRoot(newRoot); }
private async Task<Document> AddNonSerializedAttribute(Document document, SyntaxNode fieldNode, CancellationToken cancellationToken) { var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var attr = editor.Generator.Attribute(editor.Generator.TypeExpression(WellKnownTypes.NonSerializedAttribute(editor.SemanticModel.Compilation))); editor.AddAttribute(fieldNode, attr); return editor.GetChangedDocument(); }
private static void AddCodeFixWithNewPublicConstructor(CodeFixContext context, SyntaxNode root, Diagnostic diagnostic, ClassDeclarationSyntax classNode) { // Generated from http://roslynquoter.azurewebsites.net/ var constructor = SyntaxFactory.ConstructorDeclaration(classNode.Identifier) .WithModifiers( SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .WithParameterList(SyntaxFactory.ParameterList() .WithOpenParenToken( SyntaxFactory.Token(SyntaxKind.OpenParenToken)) .WithCloseParenToken( SyntaxFactory.Token( SyntaxKind.CloseParenToken))) .WithBody(SyntaxFactory.Block() .WithOpenBraceToken( SyntaxFactory.Token( SyntaxKind.OpenBraceToken)) .WithCloseBraceToken( SyntaxFactory.Token( SyntaxKind.CloseBraceToken))).NormalizeWhitespace().WithAdditionalAnnotations(Formatter.Annotation); var newClassNode = classNode.AddMembers(constructor); var newRoot = root.ReplaceNode(classNode, newClassNode); context.RegisterCodeFix( CodeAction.Create( CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription, _ => Task.FromResult(context.Document.WithSyntaxRoot(newRoot)), CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription), diagnostic); }
public static SyntaxNode AddWarningCommentIf(this SyntaxGenerator g, bool condition, SyntaxNode node) { if (condition) return g.AddWarningComment(node); else return node; }
static SA1122CodeFixProvider() { var identifierNameSyntax = SyntaxFactory.IdentifierName(nameof(string.Empty)); var stringKeyword = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)); StringEmptyExpression = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, stringKeyword, identifierNameSyntax) .WithoutFormatting(); }
private static void AddCodeFix(CodeFixContext context, SyntaxNode root, Diagnostic diagnostic, ClassDeclarationSyntax classNode) { var newRoot = IsBusinessObjectSerializableMakeSerializableCodeFix.AddAttribute( root, classNode, IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SerializableName); if (!root.HasUsing(IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SystemNamespace)) { newRoot = (newRoot as CompilationUnitSyntax).AddUsings( SyntaxFactory.UsingDirective(SyntaxFactory.ParseName( IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SystemNamespace))); } if (!root.HasUsing(IsBusinessObjectSerializableMakeSerializableCodeFixConstants.CslaSerializationNamespace)) { newRoot = (newRoot as CompilationUnitSyntax).AddUsings( SyntaxFactory.UsingDirective(SyntaxFactory.ParseName( IsBusinessObjectSerializableMakeSerializableCodeFixConstants.CslaSerializationNamespace))); } context.RegisterCodeFix( CodeAction.Create( IsBusinessObjectSerializableMakeSerializableCodeFixConstants.AddSerializableAndUsingDescription, _ => Task.FromResult<Document>(context.Document.WithSyntaxRoot(newRoot))), diagnostic); }
public IEnumerable<IHalsteadMetrics> Calculate(SyntaxNode root) { var analyzer = new HalsteadAnalyzer(); var childNodes = root.ChildNodes().AsArray(); var types = childNodes.Where(n => n.IsKind(SyntaxKind.ClassDeclaration) || n.IsKind(SyntaxKind.StructDeclaration)) .AsArray(); var methods = types.SelectMany(n => n.ChildNodes().Where(_isMethod)); var getProperties = types.SelectMany(n => n.ChildNodes().Where(IsGetProperty)); var setProperties = types.SelectMany(n => n.ChildNodes().Where(IsSetProperty)); var looseMethods = childNodes.Where(_isMethod); var looseGetProperties = childNodes.Where(IsGetProperty); var looseSetProperties = childNodes.Where(IsSetProperty); var members = methods.Concat(getProperties) .Concat(setProperties) .Concat(looseMethods) .Concat(looseGetProperties) .Concat(looseSetProperties) .AsArray(); if (members.Any()) { return members.Select(analyzer.Calculate); } var statements = childNodes.Length == 0 ? root.DescendantNodesAndTokens().Select(x => SyntaxFactory.ParseStatement(x.ToFullString(), 0, new CSharpParseOptions(kind: SourceCodeKind.Script, preprocessorSymbols: new string[0]))) : childNodes.Select(x => SyntaxFactory.ParseStatement(x.ToFullString(), 0, new CSharpParseOptions(kind: SourceCodeKind.Script, preprocessorSymbols: new string[0]))); var fakeMethod = SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "fake") .WithBody(SyntaxFactory.Block(statements)); return new[] { analyzer.Calculate(fakeMethod) }; }
internal static bool HasFlagsAttribute(SyntaxNode node, SemanticModel semanticModel) { var symbol = semanticModel.GetDeclaredSymbol(node); return symbol != null && symbol.GetAttributes().Any(attribute => attribute.AttributeClass.Is(KnownType.System_FlagsAttribute)); }
public override void Visit(Microsoft.CodeAnalysis.SyntaxNode node) { tabs++; if (node.Kind() != SyntaxKind.CompilationUnit) { var indents = new String(' ', tabs * tabWidth); if (_configurationOptions.DisplayFormattedOutput) { Messages.AppendLine(string.Format("Node:{0}{1}:>{2}<", indents, _configurationOptions.DisplayNodeKind ? node.Kind().ToString() : "", _configurationOptions.DisplayNodeValue ? node.ToString() : "")); } else { Messages.AppendLine(string.Format("Node:{0}:>{1}<", _configurationOptions.DisplayNodeKind ? node.Kind().ToString() : "", _configurationOptions.DisplayNodeValue ? node.ToString() : "")); } } // Call base to visit children base.Visit(node); tabs--; }
internal static Symbol GetDeclaredSymbolFromSyntaxNode( this CSharpSemanticModel model, Microsoft.CodeAnalysis.SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken) ) { // NOTE: Do not add types to this condition unless you have verified that there is an overload of SemanticModel.GetDeclaredSymbol // that supports the type you're adding. if ( !( declaration is AnonymousObjectCreationExpressionSyntax || declaration is AnonymousObjectMemberDeclaratorSyntax || declaration is BaseTypeDeclarationSyntax || declaration is CatchDeclarationSyntax || declaration is ExternAliasDirectiveSyntax || declaration is ForEachStatementSyntax || declaration is JoinIntoClauseSyntax || declaration is LabeledStatementSyntax || declaration is MemberDeclarationSyntax || declaration is NamespaceDeclarationSyntax || declaration is ParameterSyntax || declaration is QueryClauseSyntax || declaration is QueryContinuationSyntax || declaration is SwitchLabelSyntax || declaration is TypeParameterSyntax || declaration is UsingDirectiveSyntax || declaration is VariableDeclaratorSyntax ) ) { throw new NotSupportedException("This node type is not supported."); } return((Symbol)model.GetDeclaredSymbol(declaration, cancellationToken)); }
private SyntaxToken AnnotationResolver( SyntaxNode node, TriviaLocation location, SyntaxAnnotation annotation, SyntaxNode callsite, MethodDeclarationSyntax method) { var token = node.GetAnnotatedNodesAndTokens(annotation).FirstOrDefault().AsToken(); if (token.RawKind != 0) { return token; } switch (location) { case TriviaLocation.BeforeBeginningOfSpan: return callsite.GetFirstToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true); case TriviaLocation.AfterEndOfSpan: return callsite.GetLastToken(includeZeroWidth: true).GetNextToken(includeZeroWidth: true); case TriviaLocation.AfterBeginningOfSpan: return method.Body.OpenBraceToken.GetNextToken(includeZeroWidth: true); case TriviaLocation.BeforeEndOfSpan: return method.Body.CloseBraceToken.GetPreviousToken(includeZeroWidth: true); } return Contract.FailWithReturn<SyntaxToken>("can't happen"); }
private static bool IsInitializer(SyntaxNode node) { return node.IsKind(SyntaxKind.ArrayInitializerExpression) || node.IsKind(SyntaxKind.CollectionInitializerExpression) || node.IsKind(SyntaxKind.AnonymousObjectCreationExpression) || node.IsKind(SyntaxKind.ObjectInitializerExpression); }
/// <summary> /// When getting information for a symbol that resolves to a method group or property group, /// from which a method is then chosen; the chosen method or property is present in Symbol; /// all methods in the group that was consulted are placed in this property. /// </summary> protected abstract ImmutableArray<ISymbol> GetMemberGroupCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken));
public static IAliasSymbol GetAliasInfo(this SemanticModel semanticModel, SyntaxNode nameSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return(semanticModel.GetAliasInfo(nameSyntax, cancellationToken)); }
public static string GetIndent(Ide.Editor.TextEditor editor, Microsoft.CodeAnalysis.SyntaxNode member) { return(GetWhitespaces(editor, member.SpanStart)); }
private void Work() { string text = string.Empty; TargetLanguage language = TargetLanguage.VB;; System.Threading.ManualResetEvent[] events2 = { doCancel, doConvert }; while (true) { var evIndex = System.Threading.WaitHandle.WaitAny(events2); switch (evIndex) { case 0: return; case 1: #region { doConvert.Reset(); evIndex = System.Threading.WaitHandle.WaitAny(events2, _ConvertStartDelay); if (evIndex == 0) { return; } if (evIndex == 1) { continue; } text = this.InputText; this.OutputText = ""; language = this.InputLanguage; changed = false; doConvert.Reset(); if (string.IsNullOrWhiteSpace(text)) { Result = null; continue; } this.root = null; try { Item item; if (this.InputLanguage == TargetLanguage.VB) { var vbTree = VB.VisualBasicSyntaxTree.ParseText(text); var vbRoot = (VB.VisualBasicSyntaxNode)vbTree.GetRoot(); var vbRoot2 = vbRoot.NormalizeWhitespace(); this.OutputText = vbRoot2.ToFullString(); item = Item.Create(vbRoot); this.root = vbRoot; } else { var csTree = CS.CSharpSyntaxTree.ParseText(this.InputText); var csRoot = (CS.CSharpSyntaxNode)csTree.GetRoot(); Gekka.Roslyn.Translator.CS2VB.ResetCounter(); var vbRoot = Gekka.Roslyn.Translator.CS2VB.Translate(text).NormalizeWhitespace(); this.OutputText = vbRoot.ToFullString(); item = Item.Create(csRoot); this.root = csRoot; } this.Result = item; this.doSelect.Set(); GenerateItems(item); canSetSelection = true; } catch (Exception ex) { OutputText = ex.Message; } } #endregion break; case 2: #region { this.doSelect.Reset(); //var sel = this.InputSelection; //var result = this.Result; //var root = this.root; //if (result != null && root != null && sel != null) //{ // var item = Find(result.Items, sel); // if (item != null) // { // } //} } #endregion break; default: break; } } }
public static IAliasSymbol GetSpeculativeAliasInfo(this SemanticModel semanticModel, int position, SyntaxNode nameSyntax, SpeculativeBindingOption bindingOption) { return(semanticModel.GetSpeculativeAliasInfo(position, nameSyntax, bindingOption)); }
public static SymbolInfo GetSpeculativeSymbolInfo(this SemanticModel semanticModel, int position, SyntaxNode expression, SpeculativeBindingOption bindingOption) { return(semanticModel.GetSpeculativeSymbolInfo(position, expression, bindingOption)); }
public static DataFlowAnalysis AnalyzeDataFlow(this SemanticModel semanticModel, SyntaxNode firstStatement, SyntaxNode lastStatement) { return(semanticModel.AnalyzeDataFlow(firstStatement, lastStatement)); }
public static TypeInfo GetTypeInfo(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) { return(semanticModel.GetTypeInfo(node, cancellationToken)); }
public static ImmutableArray <ISymbol> GetMemberGroup(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) { return(semanticModel.GetMemberGroup(node, cancellationToken)); }
public static DataFlowAnalysis AnalyzeDataFlow(this SemanticModel semanticModel, SyntaxNode statementOrExpression) { return(semanticModel.AnalyzeDataFlow(statementOrExpression)); }
// return a set of text changes that when applied to the old document produces the new document internal static IList <TextChange> GetTextChanges(SyntaxNode oldNode, SyntaxNode newNode) { return(new SyntaxDiffer(oldNode, newNode, computeNewText: true).ComputeTextChangesFromOld()); }
public static ControlFlowAnalysis AnalyzeControlFlow(this SemanticModel semanticModel, SyntaxNode statement) { return(semanticModel.AnalyzeControlFlow(statement)); }
internal SeparatedSyntaxList(SyntaxNode node, int index) : this(new SyntaxNodeOrTokenList(node, index)) { }
public static ISymbol GetDeclaredSymbol(this SemanticModel semanticModel, SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken)) { return(semanticModel.GetDeclaredSymbolForNode(declaration, cancellationToken)); }
/// <summary> /// Takes a Symbol and syntax for one of its declaring syntax reference and returns the topmost syntax node to be used by syntax analyzer. /// </summary> protected internal virtual SyntaxNode GetTopmostNodeForDiagnosticAnalysis(ISymbol symbol, SyntaxNode declaringSyntax) { return declaringSyntax; }
public static bool SaveFileChanges(RewriteFileCommandConfiguration commandConfiguration, Microsoft.CodeAnalysis.SyntaxNode newNode) { Boolean performedReplacement = false; if (newNode != commandConfiguration.SyntaxTree.GetRoot()) { string fileSuffix = commandConfiguration.CodeAnalysisOptions.AddFileSuffix ? commandConfiguration.CodeAnalysisOptions.FileSuffix : ""; string newFilePath = commandConfiguration.FilePath + fileSuffix; File.WriteAllText(newFilePath, newNode.ToFullString()); performedReplacement = true; } return(performedReplacement); }
/// <summary> /// If <paramref name="nameSyntax"/> is an identifier name syntax node, return the <see cref="PreprocessingSymbolInfo"/> corresponding /// to it. /// </summary> /// <param name="nameSyntax">The nameSyntax node to get semantic information for.</param> protected abstract PreprocessingSymbolInfo GetPreprocessingSymbolInfoCore(SyntaxNode nameSyntax);
protected abstract IOperation GetOperationCore(SyntaxNode node, CancellationToken cancellationToken);
/// <summary> /// Analyze data-flow within a part of a method body. /// </summary> /// <param name="statementOrExpression">The statement or expression to be analyzed.</param> /// <returns>An object that can be used to obtain the result of the data flow analysis.</returns> /// <exception cref="System.ArgumentException">The statement or expression is not with a method /// body or field or property initializer.</exception> /// <remarks> /// The statement or expression must be fully inside a method body. /// </remarks> protected abstract DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode statementOrExpression);
/// <summary> /// Takes a node and returns a set of declarations that overlap the node's span. /// </summary> internal abstract void ComputeDeclarationsInNode(SyntaxNode node, bool getSymbol, ArrayBuilder<DeclarationInfo> builder, CancellationToken cancellationToken, int? levelsToCompute = null);
/// <summary> /// Analyze data-flow within a part of a method body. /// </summary> /// <param name="firstStatement">The first node to be included within the analysis.</param> /// <param name="lastStatement">The last node to be included within the analysis.</param> /// <returns>An object that can be used to obtain the result of the data flow analysis.</returns> /// <exception cref="System.ArgumentException">The span is not with a method /// body.</exception> /// <remarks> /// The first and last nodes must be fully inside the same method body. /// </remarks> protected abstract DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode firstStatement, SyntaxNode lastStatement);
/// <summary> /// If <paramref name="nameSyntax"/> is an identifier name syntax node, return the <see cref="PreprocessingSymbolInfo"/> corresponding /// to it. /// </summary> /// <param name="nameSyntax">The nameSyntax node to get semantic information for.</param> public PreprocessingSymbolInfo GetPreprocessingSymbolInfo(SyntaxNode nameSyntax) { return GetPreprocessingSymbolInfoCore(nameSyntax); }
/// <summary> /// Analyze data-flow within a part of a method body. /// </summary> /// <param name="statementOrExpression">The statement or expression to be analyzed.</param> /// <returns>An object that can be used to obtain the result of the data flow analysis.</returns> /// <exception cref="System.ArgumentException">The statement or expression is not with a method /// body or field or property initializer.</exception> /// <remarks> /// The statement or expression must be fully inside a method body. /// </remarks> internal DataFlowAnalysis AnalyzeDataFlow(SyntaxNode statementOrExpression) { return AnalyzeDataFlowCore(statementOrExpression); }
/// <summary> /// If the node provided has a constant value an Optional value will be returned with /// HasValue set to true and with Value set to the constant. If the node does not have an /// constant value, an Optional will be returned with HasValue set to false. /// </summary> protected abstract Optional<object> GetConstantValueCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken));
IParameterHintingData IParameterHintingDataFactory.CreateIndexerParameterDataProvider(Microsoft.CodeAnalysis.IPropertySymbol indexer, Microsoft.CodeAnalysis.SyntaxNode resolvedNode) { return(new ParameterHintingData(indexer)); }
/// <summary> /// When getting information for a symbol that resolves to a method group or property group, /// from which a method is then chosen; the chosen method or property is present in Symbol; /// all methods in the group that was consulted are placed in this property. /// </summary> internal ImmutableArray<ISymbol> GetMemberGroup(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) { return GetMemberGroupCore(node, cancellationToken); }
/// <summary> /// Analyze data-flow within a part of a method body. /// </summary> /// <param name="firstStatement">The first node to be included within the analysis.</param> /// <param name="lastStatement">The last node to be included within the analysis.</param> /// <returns>An object that can be used to obtain the result of the data flow analysis.</returns> /// <exception cref="System.ArgumentException">The span is not with a method /// body.</exception> /// <remarks> /// The first and last nodes must be fully inside the same method body. /// </remarks> internal DataFlowAnalysis AnalyzeDataFlow(SyntaxNode firstStatement, SyntaxNode lastStatement) { return AnalyzeDataFlowCore(firstStatement, lastStatement); }
/// <summary> /// If the node provided has a constant value an Optional value will be returned with /// HasValue set to true and with Value set to the constant. If the node does not have an /// constant value, an Optional will be returned with HasValue set to false. /// </summary> public Optional<object> GetConstantValue(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) { return GetConstantValueCore(node, cancellationToken); }