예제 #1
0
        public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
        {
            UsingDirectiveSyntax[] usingNodes = node.ChildNodes().Where(x => x.Kind == SyntaxKind.UsingDirective).Cast<UsingDirectiveSyntax>().ToArray();
            NamespaceDeclarationSyntax namespaceNode = (NamespaceDeclarationSyntax)node.ChildNodes().FirstOrDefault(x => x.Kind == SyntaxKind.NamespaceDeclaration);

            if (usingNodes.Length > 0 && namespaceNode != null)
            {
                SyntaxTriviaList leadingTrivia = usingNodes[0].GetLeadingTrivia();

                // Remove the existing using statements.
                node = node.ReplaceNodes(usingNodes, (a, b) => null);

                // Leading comment trivia will be added to the namespace. This allows file comments
                // to remain at the top of the file.
                var namespaceTrivia = leadingTrivia.TakeWhile(x =>
                    x.Kind == SyntaxKind.SingleLineCommentTrivia ||
                    x.Kind == SyntaxKind.EndOfLineTrivia);

                // All other trivia will be preserved on the first using directive.
                var preservedTrivia = leadingTrivia.Skip(namespaceTrivia.Count());
                usingNodes[0] = usingNodes[0].WithLeadingTrivia(preservedTrivia);

                // Leading trivia from the namespace needs to be added as trailing trivia to the
                // last using. This allows for #regions around the using statements (as of the
                // Roslyn Sept 2012 CTP, the #endregion appears as leading trivia on the namespace)
                // TODO: See if this is still necessary with the next CTP.
                var trailingTrivia = usingNodes.Last().GetTrailingTrivia()
                    .Concat(namespaceNode.GetLeadingTrivia());

                usingNodes[usingNodes.Length - 1] = usingNodes.Last().WithTrailingTrivia(trailingTrivia);

                // Add any using directives already on the namespace.
                var namespaceUsings = usingNodes.Concat(namespaceNode.Usings);

                // Create a new namespace statment with the usings and the leading trivia we removed earlier.
                SyntaxNode newNamespaceNode = namespaceNode
                    .WithUsings(Syntax.List<UsingDirectiveSyntax>(namespaceUsings))
                    .WithLeadingTrivia(namespaceTrivia);

                // Replace the namespace with the one with usings.
                node = node.ReplaceNodes(
                    node.ChildNodes().Take(1),
                    (a, b) => newNamespaceNode);

            }

            return node;
        }
 public static List <string> GetUsings(this CompilationUnitSyntax root)
 {
     return(root.ChildNodes()
            .OfType <UsingDirectiveSyntax>()
            .Select(n => n.Name.ToString())
            .ToList());
 }
예제 #3
0
        protected string GenerateToStringMethod(ClassDeclarationSyntax target, Compilation compilation)
        {
            CompilationUnitSyntax root = target.SyntaxTree.GetCompilationUnitRoot();

            StringBuilder builder = new StringBuilder();

            builder.AppendLine($"using {Attribute.Namespace};");
            builder.AppendLine($"namespace {root.ChildNodes().OfType<NamespaceDeclarationSyntax>().First().Name}");
            builder.AppendLine("{");
            builder.AppendLine($"{target.Modifiers} class {target.Identifier.Text}");
            builder.AppendLine("{");
            builder.AppendLine("public override string ToString()");
            builder.AppendLine("{");
            builder.AppendLine("var builder = new System.Text.StringBuilder();");

            foreach (PropertyDeclarationSyntax property in target.Members.OfType <PropertyDeclarationSyntax>())
            {
                string name = property.Identifier.Text;
                builder.AppendLine($"builder.AppendLine(\"{name}:\" + {name}.ToString());");
            }

            builder.AppendLine("return builder.ToString();");
            builder.AppendLine("}");
            builder.AppendLine("}");
            builder.AppendLine("}");

            return(builder.ToString());
        }
예제 #4
0
        public override void VisitCompilationUnit(CompilationUnitSyntax compilationUnit)
        {
            foreach (var m in compilationUnit.ChildNodes())
            {
                Cx.Try(m, null, () => ((CSharpSyntaxNode)m).Accept(this));
            }

            ExtractGlobalStatements(compilationUnit);

            // Gather comments:
            foreach (var trivia in compilationUnit.DescendantTrivia(compilationUnit.Span, descendIntoTrivia: true))
            {
                CommentPopulator.ExtractComment(Cx, trivia);
            }

            foreach (var trivia in compilationUnit.GetLeadingTrivia())
            {
                CommentPopulator.ExtractComment(Cx, trivia);
            }

            foreach (var trivia in compilationUnit.GetTrailingTrivia())
            {
                CommentPopulator.ExtractComment(Cx, trivia);
            }
        }
예제 #5
0
 private static bool ShouldSuppressDiagnostic(CompilationUnitSyntax compilationUnit)
 {
     // Suppress if there are nodes other than usings and namespaces in the
     // compilation unit (including ExternAlias).
     return(compilationUnit.ChildNodes().Any(
                t => !t.IsKind(SyntaxKind.UsingDirective, SyntaxKind.NamespaceDeclaration)));
 }
예제 #6
0
        public TypeDefinition GenerateTypeDefinition(CompilationUnitSyntax rootNode)
        {
            var _inputNamespaceDeclaration = rootNode
                                             .ChildNodes()
                                             .Where(_syntaxNode => _syntaxNode is CSharpSyntaxNode)
                                             .OfType <NamespaceDeclarationSyntax>()
                                             .OneOrDefault();

            var _inputClassDeclaration = _inputNamespaceDeclaration?
                                         .ChildNodes()
                                         .Where(_syntaxNode => _syntaxNode is CSharpSyntaxNode)
                                         .OfType <ClassDeclarationSyntax>()
                                         .Where(_classDeclaration => _classDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword))
                                         .Where(_classDeclaration => _classDeclaration.HasLeadingTrivia)
                                         .OneOrDefault();

            var _immutablerDocumentationXml = _inputClassDeclaration?
                                              .GetLeadingTrivia()
                                              .Where(_trivia => _trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia)
                                              .Select(_trivia => _trivia.GetStructure().ToString())
                                              .Select(_ParseDocumentationCommentXml)
                                              .Where(_xml => string.Equals(_xml?.Name.LocalName, "Immutabler", StringComparison.Ordinal))
                                              .OneOrDefault();

            if (_immutablerDocumentationXml == null)
            {
                return(null);
            }

            return(_CreateTypeDefinition(_inputClassDeclaration, rootNode));
        }
 public static string GetNamespace(this CompilationUnitSyntax root)
 {
     return(root.ChildNodes()
            .OfType <NamespaceDeclarationSyntax>()
            .FirstOrDefault()
            .Name
            .ToString());
 }
예제 #8
0
        public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
        {
            var attributes = GetCompileAttributeList(SyntaxFactory.List(node.ChildNodes().OfType <AttributeListSyntax>()));

            foreach (var attribute in attributes)
            {
                _assemblyAttributes.Add(attribute);
            }

            return(base.VisitCompilationUnit(node));
        }
예제 #9
0
        private static IEnumerable <TypeDeclarationSyntax> GetTypeDeclarationNodes(
            CompilationUnitSyntax root,
            Func <TypeDeclarationSyntax, bool> predicate)
        {
            var candidateTypes =
                from t in root.ChildNodes().OfType <TypeDeclarationSyntax>().ToList()
                where predicate(t)
                select t;

            return(candidateTypes);
        }
예제 #10
0
        public static Tests[] GenerateTests(string textProgram)
        {
            List <Tests>          tests      = new List <Tests>();
            SyntaxTree            syntaxTree = CSharpSyntaxTree.ParseText(textProgram);
            CompilationUnitSyntax Root       = syntaxTree.GetCompilationUnitRoot();
            var namespaces = Root.ChildNodes().Where(@namespace => @namespace is NamespaceDeclarationSyntax);

            foreach (NamespaceDeclarationSyntax @namespace in namespaces)
            {
                FindMethod(@namespace, Root, ref tests);
            }
            return(tests.ToArray());
        }
예제 #11
0
        /// <summary>
        /// Adds the string specified using statement to the CompilationUnitSyntax if that using is not already present.
        /// </summary>
        /// <remarks>
        /// The using statement, if inserted, will be followed by a CR/LF.
        /// </remarks>
        /// <param name="unit">
        /// The type being extended.
        /// </param>
        /// <param name="usingString">
        /// The string statement such as "System.Diagnostics" or "Microsoft.CodeAnalysis.CSharp.Syntax".
        /// </param>
        /// <returns>
        /// The CompilationUnitSyntax in <paramref name="unit"/>.
        /// </returns>
        public static CompilationUnitSyntax AddUsingIfNotPresent(this CompilationUnitSyntax unit, String usingString)
        {
            var t = unit.ChildNodes().OfType <UsingDirectiveSyntax>().Where(u => u.Name.ToString().Equals(usingString));

            if (!t.Any())
            {
                UsingDirectiveSyntax usingDirective = SyntaxFactoryHelper.QualifiedUsing(usingString);

                // I'll never understand why WithAdditionalAnnotations(Formatter.Annotation) isn't the default. Picking
                // up the default formatting should be the default and would make developing rules much easier.
                unit = unit.AddUsings(usingDirective).WithAdditionalAnnotations(Formatter.Annotation);
            }
            return(unit);
        }
예제 #12
0
        private static void HandleCompilationUnit(SyntaxNodeAnalysisContext context, StyleCopSettings settings)
        {
            if (settings.OrderingRules.UsingDirectivesPlacement != UsingDirectivesPlacement.InsideNamespace)
            {
                return;
            }

            CompilationUnitSyntax syntax = (CompilationUnitSyntax)context.Node;

            List <SyntaxNode> usingDirectives = new List <SyntaxNode>();

            foreach (SyntaxNode child in syntax.ChildNodes())
            {
                switch (child.Kind())
                {
                case SyntaxKind.ClassDeclaration:
                case SyntaxKind.InterfaceDeclaration:
                case SyntaxKind.EnumDeclaration:
                case SyntaxKind.StructDeclaration:
                case SyntaxKind.DelegateDeclaration:
                    // Suppress SA1200 if file contains a type in the global namespace
                    return;

                case SyntaxKind.AttributeList:
                    // Suppress SA1200 if file contains an attribute in the global namespace
                    return;

                case SyntaxKind.GlobalStatement:
                    // Suppress SA1200 if file contains top-level statements
                    return;

                case SyntaxKind.UsingDirective:
                    usingDirectives.Add(child);
                    continue;

                case SyntaxKind.ExternAliasDirective:
                case SyntaxKind.NamespaceDeclaration:
                case SyntaxKindEx.FileScopedNamespaceDeclaration:
                default:
                    continue;
                }
            }

            foreach (var directive in usingDirectives)
            {
                // Using directive should appear within a namespace declaration
                context.ReportDiagnostic(Diagnostic.Create(DescriptorInside, directive.GetLocation()));
            }
        }
        internal static CompilationUnitSyntax AddUsings(this CompilationUnitSyntax compilationUnit, params string[] usings)
        {
            foreach (var @using in usings)
            {
                var needsUsing = !compilationUnit.ChildNodes().OfType <UsingDirectiveSyntax>().Any(u => u.Name.ToString().Equals(@using));

                if (needsUsing)
                {
                    var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(@using));
                    compilationUnit = compilationUnit.AddUsings(usingDirective).WithAdditionalAnnotations(Formatter.Annotation);
                }
            }

            return(compilationUnit);
        }
예제 #14
0
        /// <summary>
        /// Executes the transformation and returns the contents of the generated output file.
        /// </summary>
        /// <param name="inputText">The contents of the input file.</param>
        /// <param name="filePath">The full path of the input file.</param>
        /// <param name="defaultNamespace">The namespace into which the generated code will be placed.</param>
        /// <returns>The contents of the output file.</returns>
        protected override string GenerateCode(string inputText, string filePath, string defaultNamespace)
        {
            CompilationUnitSyntax unit1 = SyntaxFactory.CompilationUnit();

            CompilationUnitSyntax unit2 = CSharpSyntaxTree.ParseText(inputText).GetCompilationUnitRoot();

            NamespaceDeclarationSyntax[] array = GenerateNamespaces(unit2.ChildNodes().OfType <NamespaceDeclarationSyntax>()).ToArray();

            if (array.Length > 0)
            {
                unit1 = unit1.WithUsings(unit2.Usings).AddMembers(array);
            }

            return(unit1.ToFileString());
        }
예제 #15
0
        public static NamespaceDeclarationSyntax GetNamespace(SyntaxTree tree)
        {
            CompilationUnitSyntax      root          = tree.GetCompilationUnitRoot();
            NamespaceDeclarationSyntax namespaceNode = null;

            foreach (SyntaxNode child in root.ChildNodes())
            {
                if (child is NamespaceDeclarationSyntax)
                {
                    namespaceNode = (NamespaceDeclarationSyntax)child;
                    break;
                }
            }

            return(namespaceNode);
        }
예제 #16
0
        private void HandleCompilationUnitSyntax(SyntaxNodeAnalysisContext context)
        {
            CompilationUnitSyntax syntax = context.Node as CompilationUnitSyntax;

            if (syntax == null)
            {
                return;
            }

            List <SyntaxNode> usingDirectives = new List <SyntaxNode>();

            foreach (SyntaxNode child in syntax.ChildNodes())
            {
                switch (child.Kind())
                {
                case SyntaxKind.ClassDeclaration:
                case SyntaxKind.InterfaceDeclaration:
                case SyntaxKind.EnumDeclaration:
                case SyntaxKind.StructDeclaration:
                case SyntaxKind.DelegateDeclaration:
                    // Suppress SA1200 if file contains a type in the global namespace
                    return;

                case SyntaxKind.AttributeList:
                    // suppress SA1200 if file contains an attribute in the global namespace
                    return;

                case SyntaxKind.UsingDirective:
                    usingDirectives.Add(child);
                    continue;

                case SyntaxKind.ExternAliasDirective:
                case SyntaxKind.NamespaceDeclaration:
                default:
                    continue;
                }
            }

            foreach (var directive in usingDirectives)
            {
                // Using directive must appear within a namespace declaration
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, directive.GetLocation()));
            }
        }
예제 #17
0
        public static CompilationUnitSyntax ExtractClass(this CompilationUnitSyntax root, TextSpan span)
        {
            var node     = root.FindNode(span);
            var typeDecl = node as BaseTypeDeclarationSyntax;

            if (typeDecl == null)
            {
                return(null);
            }

            var member = node as MemberDeclarationSyntax;
            var namespaceDeclarations = typeDecl
                                        .Ancestors()
                                        .OfType <NamespaceDeclarationSyntax>()
                                        .Select(n => (member = n.WithMembers(SyntaxFactory.SingletonList(member))));
            var namespaceDecl = namespaceDeclarations.LastOrDefault() as MemberDeclarationSyntax;

            if (namespaceDecl == null)
            {
                namespaceDecl = typeDecl;
            }

            var usings = root
                         .DescendantNodesAndSelf(n => true)
                         .OfType <UsingDirectiveSyntax>()
                         .Select(u => u.WithAdditionalAnnotations(Simplifier.Annotation));

            var extAlias = root
                           .ChildNodes()
                           .OfType <ExternAliasDirectiveSyntax>();

            var ret = SyntaxFactory.CompilationUnit(
                SyntaxFactory.List(extAlias),
                SyntaxFactory.List(usings),
                SyntaxFactory.List <AttributeListSyntax>(),
                SyntaxFactory.SingletonList(namespaceDecl)
                );

            return(ret);
        }
        public Generator Analyse(string input)
        {
            try
            {
                SyntaxTree            tree = CSharpSyntaxTree.ParseText(input);
                CompilationUnitSyntax root = tree.GetCompilationUnitRoot();

                objectModelList = new List <ObjectModel>();

                foreach (SyntaxNode child in root.ChildNodes())
                {
                    if (child.Kind() == SyntaxKind.ClassDeclaration)
                    {
                        ObjectModel parent = new ObjectModel();
                        foreach (SyntaxToken item in child.ChildTokens())
                        {
                            if (item.Kind() == SyntaxKind.IdentifierToken)
                            {
                                parent.TokenType  = SyntaxKind.ClassDeclaration;
                                parent.SyntaxName = item.Value.ToString();
                                break;
                            }
                        }

                        if (child.ChildNodes().Count() > 0)
                        {
                            AnalyseChildNodes(child, parent);
                        }

                        objectModelList.Add(parent);
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return(this);
        }
예제 #19
0
 public override SyntaxNode VisitBlock(BlockSyntax node)
 {
     if (_applicationStart)
     {
         _applicationStart = false;
         if (_notPartialClass)
         {
             using (var globalModelSR = new StreamReader(_globalAsaxCsModelPath))
             {
                 _globalModel = globalModelSR.ReadToEnd();
             }
             _globalModelCompilationUnit = SyntaxFactory.ParseCompilationUnit(_globalModel);
             var globalModelNamespace            = _globalModelCompilationUnit.ChildNodes().OfType <NamespaceDeclarationSyntax>().First();
             var globalModelClass                = globalModelNamespace.ChildNodes().OfType <ClassDeclarationSyntax>().First();
             var globalModelApplicationStart     = globalModelClass.ChildNodes().OfType <MethodDeclarationSyntax>().First(m => m.Identifier.ValueText == "Application_Start");
             var globalModelApplicationStartBody = globalModelApplicationStart.Body;
             node = node.AddStatements(globalModelApplicationStartBody.Statements.ToArray());
         }
         return(node.AddStatements(SyntaxFactory.ParseStatement("Global." + _edmxName + "ApplicationStart(unityContainer);")));
     }
     return(base.VisitBlock(node));
 }
        /// <summary>
        /// Updateshouldies the using directive.
        /// </summary>
        /// <param name="compilationUnit">The compilation unit.</param>
        /// <returns></returns>
        protected CompilationUnitSyntax UpdateShouldyUsingDirective(CompilationUnitSyntax compilationUnit)
        {
            var usingDirectiveAlreadyExists = compilationUnit.DescendantNodes().Any(x =>
            {
                if (x.Kind() != SyntaxKind.UsingDirective)
                {
                    return(false);
                }

                return((x as UsingDirectiveSyntax).Name.GetText().ToString() == SHOULDLY_NAMESPACE);
            });

            if (usingDirectiveAlreadyExists)
            {
                return(compilationUnit);
            }

            var namespaceDeclaration = compilationUnit.ChildNodes().FirstOrDefault(x => x.Kind() == SyntaxKind.NamespaceDeclaration) as NamespaceDeclarationSyntax;
            var addUsingToNamespace  = false;

            if (!(namespaceDeclaration is null))
            {
                addUsingToNamespace = namespaceDeclaration.Usings.Any();
            }

            var shouldlyIdentifier = SyntaxFactory.IdentifierName("Shouldly");
            var usingShouldly      = SyntaxFactory.UsingDirective(shouldlyIdentifier);

            if (addUsingToNamespace)
            {
                var newNamespaceDeclaration = namespaceDeclaration.AddUsings(usingShouldly);
                return(compilationUnit.ReplaceNode(namespaceDeclaration, newNamespaceDeclaration));
            }
            else
            {
                return(compilationUnit.AddUsings(usingShouldly));
            }
        }
예제 #21
0
        public void InsertNode()
        {
            string                 text      = "class C { void M() { } }";
            SyntaxTree             tree      = SyntaxFactory.ParseSyntaxTree(text);
            CompilationUnitSyntax  root      = (CompilationUnitSyntax)tree.GetRoot();
            ClassDeclarationSyntax classNode = root.ChildNodes().First() as ClassDeclarationSyntax;

            MethodDeclarationSyntax newMethod = SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName("int"), SyntaxFactory.Identifier("NewMethod"))
                                                .WithBody(SyntaxFactory.Block());

            SyntaxList <MemberDeclarationSyntax> newMembers = SyntaxFactory.List <MemberDeclarationSyntax>(classNode.Members.Concat(new[] { newMethod }));

            ClassDeclarationSyntax newClass = SyntaxFactory.ClassDeclaration(
                classNode.AttributeLists,
                classNode.Modifiers,
                classNode.Keyword,
                classNode.Identifier,
                classNode.TypeParameterList,
                classNode.BaseList,
                classNode.ConstraintClauses,
                classNode.OpenBraceToken,
                newMembers,
                classNode.CloseBraceToken,
                classNode.SemicolonToken).NormalizeWhitespace(elasticTrivia: true);

            root = root.ReplaceNode(classNode, newClass);
            tree = tree.WithRootAndOptions(root, tree.Options);
            Assert.Equal(@"class C
{
    void M()
    {
    }

    int NewMethod()
    {
    }
}", tree.GetText().ToString());
        }
예제 #22
0
        public override void VisitCompilationUnit(CompilationUnitSyntax compilationUnit)
        {
            foreach (var m in compilationUnit.ChildNodes())
            {
                cx.Try(m, null, () => ((CSharpSyntaxNode)m).Accept(this));
            }

            // Gather comments:
            foreach (SyntaxTrivia trivia in compilationUnit.DescendantTrivia(compilationUnit.Span))
            {
                CommentLine.Extract(cx, trivia);
            }

            foreach (var trivia in compilationUnit.GetLeadingTrivia())
            {
                CommentLine.Extract(cx, trivia);
            }

            foreach (var trivia in compilationUnit.GetTrailingTrivia())
            {
                CommentLine.Extract(cx, trivia);
            }
        }
예제 #23
0
        private void ExtractGlobalStatements(CompilationUnitSyntax compilationUnit)
        {
            var globalStatements = compilationUnit
                                   .ChildNodes()
                                   .OfType <GlobalStatementSyntax>()
                                   .ToList();

            if (!globalStatements.Any())
            {
                return;
            }

            var entryPoint  = Cx.Compilation.GetEntryPoint(System.Threading.CancellationToken.None);
            var entryMethod = Method.Create(Cx, entryPoint);
            var block       = GlobalStatementsBlock.Create(Cx, entryMethod);

            for (var i = 0; i < globalStatements.Count; i++)
            {
                if (globalStatements[i].Statement is object)
                {
                    Statement.Create(Cx, globalStatements[i].Statement, block, i);
                }
            }
        }
예제 #24
0
 public override string VisitCompilationUnit(CompilationUnitSyntax node)
 {
     return(Visit(node.ChildNodes().OfType <NamespaceDeclarationSyntax>().FirstOrDefault()));
 }
예제 #25
0
 public static List <ClassDeclarationSyntax> classes(this CompilationUnitSyntax compilationUnit)
 {
     return(compilationUnit.ChildNodes()
            .OfType <ClassDeclarationSyntax>().toList());
 }
예제 #26
0
 public static string GetNamespace(this CompilationUnitSyntax root)
 => root.ChildNodes()
 .OfType <NamespaceDeclarationSyntax>()
 .First().Name.ToString();