public override int GetComplexity(SyntaxNode node) { var possibleNodes = node .DescendantNodesAndSelf() .Where(n => !n.Parent.IsKind(SyntaxKind.InterfaceBlock) && ComplexityIncreasingKinds.Contains(n.Kind())); return possibleNodes.Count(n => !IsFunctionLikeLastReturnStatement(n)); }
public override IEnumerable<SyntaxNode> GetDescendantMemberAccessExpressionNodes(SyntaxNode node) { IEnumerable<SyntaxNode> empty = Enumerable.Empty<SyntaxNode>(); if (node == null) { return empty; } return node.DescendantNodesAndSelf().OfType<MemberAccessExpressionSyntax>(); }
public static int Complexity(SyntaxNode node) { return node .DescendantNodesAndSelf() .Count( n => // TODO What about the null coalescing operator? ComplexityIncreasingKinds.Contains(n.Kind()) || IsReturnButNotLast(n) || IsFunctionAndHasBlock(n)); }
private static SyntaxNode RemoveUnusedImportDirectives(SemanticModel semanticModel, SyntaxNode root, CancellationToken cancellationToken) { var oldUsings = root.DescendantNodesAndSelf().Where(s => s is UsingDirectiveSyntax); var unusedUsings = GetUnusedImportDirectives(semanticModel, cancellationToken); SyntaxTriviaList leadingTrivia = root.GetLeadingTrivia(); root = root.RemoveNodes(oldUsings, SyntaxRemoveOptions.KeepNoTrivia); var newUsings = SyntaxFactory.List(oldUsings.Except(unusedUsings)); root = ((CompilationUnitSyntax)root) .WithUsings(newUsings) .NormalizeWhitespace() .WithLeadingTrivia(leadingTrivia); return root; }
internal static bool IsEmpty(SyntaxNode node) { //don't include self return node == null || node.DescendantNodesAndSelf().All(d => (d is EmptyStatementSyntax || d is BlockSyntax)); }
private static IEnumerable<ElementAccessExpressionSyntax> GetElementAccessExpressions(SyntaxNode node) { return node == null ? SpecializedCollections.EmptyEnumerable<ElementAccessExpressionSyntax>() : node.DescendantNodesAndSelf().Where(s => s.IsKind(SyntaxKind.ElementAccessExpression)).Cast<ElementAccessExpressionSyntax>(); }
static bool IsSingleType (SyntaxNode root) { return root.DescendantNodesAndSelf (c => !(c is BaseTypeDeclarationSyntax)).OfType<BaseTypeDeclarationSyntax> ().Count () == 1; }
private static IEnumerable<ITypeSymbol> GetReferencedTypes(SyntaxNode classDeclaration, ISymbol sourceSymbol, SemanticModel semanticModel) { var typeSyntaxes = classDeclaration.DescendantNodesAndSelf().OfType<TypeSyntax>(); var commonSymbolInfos = typeSyntaxes.Select(x => semanticModel.GetSymbolInfo(x)).AsArray(); var members = commonSymbolInfos .Select(x => x.Symbol) .Where(x => x != null) .Select(x => { var typeSymbol = x as ITypeSymbol; return typeSymbol == null ? x.ContainingType : x; }) .Cast<ITypeSymbol>() .WhereNotNull() .DistinctBy(x => x.ToDisplayString()) .Where(x => x != sourceSymbol) .AsArray(); return members; }
private int GetEfferentCoupling(SyntaxNode classDeclaration, ISymbol sourceSymbol) { var typeSyntaxes = classDeclaration.DescendantNodesAndSelf().OfType<TypeSyntax>(); var commonSymbolInfos = typeSyntaxes.Select(x => Model.GetSymbolInfo(x)).AsArray(); var members = commonSymbolInfos .Select(x => x.Symbol) .Where(x => x != null) .Select(x => { var typeSymbol = x as ITypeSymbol; return typeSymbol == null ? x.ContainingType : x; }) .Cast<ITypeSymbol>() .WhereNotNull() .DistinctBy(x => x.ToDisplayString()) .Count(x => !x.Equals(sourceSymbol)); return members; }
private SyntaxNode FindUnsupportedV7Switch(SemanticModel model, SyntaxNode syntaxNode, List<RudeEditDiagnostic> diagnostics) { foreach (var node in syntaxNode.DescendantNodesAndSelf().Where(n => n.Kind() == SyntaxKind.SwitchStatement)) { var switchExpression = ((SwitchStatementSyntax)node).Expression; ITypeSymbol governingType = model.GetTypeInfo(switchExpression).Type; if (!IsValidV6SwitchGoverningType(governingType)) { return node; } } return null; }
private static IEnumerable<ElementAccessExpressionSyntax> GetElementAccessExpressions(SyntaxNode node) { return node == null ? new ElementAccessExpressionSyntax[0] : node.DescendantNodesAndSelf().Where(s => s.IsKind(SyntaxKind.ElementAccessExpression)).Cast<ElementAccessExpressionSyntax>(); }
SyntaxNode ISyntaxRule.Process(SyntaxNode root) { root.DescendantNodesAndSelf() .Where(n => n.IsKind(SyntaxKind.IfStatement) || n.IsKind(SyntaxKind.ElseClause)); return root; }
// public static IUnresolvedMember AddCodeDomMember (MonoDevelop.Projects.Project project, IUnresolvedTypeDefinition type, CodeTypeMember newMember) // { // bool isOpen; // var data = TextFileProvider.Instance.GetTextEditorData (type.Region.FileName, out isOpen); // var parsedDocument = TypeSystemService.ParseFile (data.FileName, data.MimeType, data.Text); // // var insertionPoints = GetInsertionPoints (data, parsedDocument, type); // // var suitableInsertionPoint = GetSuitableInsertionPoint (insertionPoints, type, newMember); // // var dotNetProject = project as DotNetProject; // if (dotNetProject == null) { // LoggingService.LogError ("Only .NET projects are supported."); // return null; // } // // var generator = dotNetProject.LanguageBinding.GetCodeDomProvider (); // StringWriter sw = new StringWriter (); // var options = new CodeGeneratorOptions (); // options.IndentString = data.GetLineIndent (type.Region.BeginLine) + "\t"; // if (newMember is CodeMemberMethod) // options.BracingStyle = "C"; // generator.GenerateCodeFromMember (newMember, sw, options); // // var code = sw.ToString (); // if (!string.IsNullOrEmpty (code)) // suitableInsertionPoint.Insert (data, code); // if (!isOpen) { // try { // File.WriteAllText (type.Region.FileName, data.Text); // } catch (Exception e) { // LoggingService.LogError (string.Format ("Failed to write file '{0}'.", type.Region.FileName), e); // MessageService.ShowError (GettextCatalog.GetString ("Failed to write file '{0}'.", type.Region.FileName)); // } // } // var newDocument = TypeSystemService.ParseFile (data.FileName, data.MimeType, data.Text); // return newDocument.ParsedFile.GetMember (suitableInsertionPoint.Location.Line, int.MaxValue); // } public static async Task AddNewMember (Projects.Project project, ITypeSymbol type, Location part, SyntaxNode newMember, CancellationToken cancellationToken = default(CancellationToken)) { if (project == null) throw new ArgumentNullException (nameof (project)); if (type == null) throw new ArgumentNullException (nameof (type)); if (newMember == null) throw new ArgumentNullException (nameof (newMember)); if (!type.IsDefinedInSource ()) throw new ArgumentException ("The given type needs to be defined in source code.", nameof (type)); var ws = MonoDevelop.Ide.TypeSystem.TypeSystemService.GetWorkspace (project.ParentSolution); var projectId = ws.GetProjectId (project); var docId = ws.GetDocumentId (projectId, part.SourceTree.FilePath); var document = ws.GetDocument (docId, cancellationToken); var root = await document.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false); var typeDecl = (ClassDeclarationSyntax)root.FindNode (part.SourceSpan); // for some reason the reducer doesn't reduce this var systemVoid = newMember.DescendantNodesAndSelf ().OfType<QualifiedNameSyntax> ().FirstOrDefault (ma => ma.ToString () == "System.Void"); if (systemVoid != null) newMember = newMember.ReplaceNode (systemVoid, SyntaxFactory.ParseTypeName ("void")); var newRoot = root.ReplaceNode (typeDecl, typeDecl.AddMembers ((MemberDeclarationSyntax)newMember.WithAdditionalAnnotations (Simplifier.Annotation, Formatter.Annotation))); document = document.WithSyntaxRoot (newRoot); var policy = project.Policies.Get<CSharpFormattingPolicy> ("text/x-csharp"); var textPolicy = project.Policies.Get<TextStylePolicy> ("text/x-csharp"); var projectOptions = policy.CreateOptions (textPolicy); document = await Formatter.FormatAsync (document, Formatter.Annotation, projectOptions, cancellationToken).ConfigureAwait (false); document = await Simplifier.ReduceAsync (document, Simplifier.Annotation, projectOptions, cancellationToken).ConfigureAwait (false); var text = await document.GetTextAsync (cancellationToken).ConfigureAwait (false); var newSolution = ws.CurrentSolution.WithDocumentText (docId, text); ws.TryApplyChanges (newSolution); }
public static async Task InsertMemberWithCursor (string operation, Projects.Project project, ITypeSymbol type, Location part, SyntaxNode newMember, CancellationToken cancellationToken = default(CancellationToken)) { if (operation == null) throw new ArgumentNullException (nameof (operation)); if (project == null) throw new ArgumentNullException (nameof (project)); if (type == null) throw new ArgumentNullException (nameof (type)); if (newMember == null) throw new ArgumentNullException (nameof (newMember)); var ws = MonoDevelop.Ide.TypeSystem.TypeSystemService.GetWorkspace (project.ParentSolution); var projectId = ws.GetProjectId (project); var docId = ws.GetDocumentId (projectId, part.SourceTree.FilePath); var document = ws.GetDocument (docId, cancellationToken); var root = await document.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false); var typeDecl = (ClassDeclarationSyntax)root.FindNode (part.SourceSpan); // for some reason the reducer doesn't reduce this var systemVoid = newMember.DescendantNodesAndSelf ().OfType<QualifiedNameSyntax> ().FirstOrDefault (ma => ma.ToString () == "System.Void"); if (systemVoid != null) newMember = newMember.ReplaceNode (systemVoid, SyntaxFactory.ParseTypeName ("void")); var newRoot = root.ReplaceNode (typeDecl, typeDecl.AddMembers ((MemberDeclarationSyntax)newMember.WithAdditionalAnnotations (Simplifier.Annotation, Formatter.Annotation, insertedMemberAnnotation))); var doc = await IdeApp.Workbench.OpenDocument (part.SourceTree.FilePath, project, true); var policy = project.Policies.Get<CSharpFormattingPolicy> ("text/x-csharp"); var textPolicy = project.Policies.Get<TextStylePolicy> ("text/x-csharp"); var projectOptions = policy.CreateOptions (textPolicy); document = document.WithSyntaxRoot (newRoot); document = await Formatter.FormatAsync (document, Formatter.Annotation, projectOptions, cancellationToken).ConfigureAwait (false); document = await Simplifier.ReduceAsync (document, Simplifier.Annotation, projectOptions, cancellationToken).ConfigureAwait (false); root = await document.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false); var node = root.GetAnnotatedNodes (insertedMemberAnnotation).Single (); Application.Invoke (async delegate { var insertionPoints = InsertionPointService.GetInsertionPoints ( doc.Editor, await doc.UpdateParseDocument (), type, part.SourceSpan.Start ); var options = new InsertionModeOptions ( operation, insertionPoints, point => { if (!point.Success) return; var text = node.ToString (); point.InsertionPoint.Insert (doc.Editor, doc, text); } ); doc.Editor.StartInsertionMode (options); }); }
private static IEnumerable<SyntaxNode> AffectedExpressions(SyntaxNode node) { return node .DescendantNodesAndSelf() .Where(n => SideEffectExpressions.Any(s => s.Kinds.Any(n.IsKind))) .Select(n => SideEffectExpressions.Single(s => s.Kinds.Any(n.IsKind)).AffectedExpression(n)); }
public override int GetComplexity(SyntaxNode node) { return node .DescendantNodesAndSelf() .Count( n => // TODO What about the null coalescing operator? ComplexityIncreasingKinds.Contains(n.Kind()) || IsReturnButNotLast(n) || IsFunctionWithBody(n)); }
public void ClassifyDeclarationBodyRudeUpdates(SyntaxNode newDeclarationOrBody) { foreach (var node in newDeclarationOrBody.DescendantNodesAndSelf(ChildrenCompiledInBody)) { switch (node.Kind()) { case SyntaxKind.StackAllocArrayCreationExpression: ReportError(RudeEditKind.StackAllocUpdate, node, _newNode); return; } } }
public void ClassifyDeclarationBodyRudeUpdates(SyntaxNode newDeclarationOrBody, bool allowLambdas) { foreach (var node in newDeclarationOrBody.DescendantNodesAndSelf(ChildrenCompiledInBody)) { switch (node.Kind()) { case SyntaxKind.StackAllocArrayCreationExpression: ReportError(RudeEditKind.StackAllocUpdate, node, _newNode); return; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: if (!allowLambdas) { // TODO (tomat): allow ReportError(RudeEditKind.RUDE_EDIT_LAMBDA_EXPRESSION, node, _newNode); return; } break; case SyntaxKind.AnonymousMethodExpression: if (!allowLambdas) { // TODO (tomat): allow ReportError(RudeEditKind.RUDE_EDIT_ANON_METHOD, node, _newNode); return; } break; case SyntaxKind.QueryExpression: if (!allowLambdas) { // TODO (tomat): allow ReportError(RudeEditKind.RUDE_EDIT_QUERY_EXPRESSION, node, _newNode); return; } break; } } }