예제 #1
0
        protected SyntaxList<ExpressionSyntax> RewritePostfixUnarys(SyntaxList<ExpressionSyntax> nodes)
        {
            if (nodes.Count == 0)
                return nodes;

            return Syntax.List (nodes.Select (RewritePostfixUnarys));
        }
예제 #2
0
    public static string GenerateNewCode(string[] duckTypes, string name, System.Collections.Immutable.ImmutableArray <ITypeParameterSymbol> typeParameters, System.Collections.Immutable.ImmutableArray <ITypeSymbol> typeArguments, TypeParameterListSyntax typeParameterList, SyntaxList <AttributeListSyntax> attributeLists, Func <CSharpSyntaxNode, string, IEnumerable <TypeParameterSyntax>, IEnumerable <AttributeListSyntax>, CSharpSyntaxNode> withDeclarationInfo, CSharpSyntaxNode ogNode, Dictionary <string, List <CSharpSyntaxNode> > newNodes)
    {
        var newName = $"GENERATED_{name}_{typeArguments.ListToString("_")}";

        var newTypeParams = typeParameterList.Parameters.Where(p => !duckTypes.Contains(p.Identifier.ToString()));

        var newAttrLists = attributeLists.
                           Select(list => AttributeList(SeparatedList(list.Attributes.Where(attr =>
                                                                                            attr.Name.ToString() != "DuckTypeAttribute" && attr.Name.ToString() != "DuckType")))).
                           Where(list => list.Attributes.Any());

        var newNode = withDeclarationInfo(ogNode, newName, newTypeParams, newAttrLists);

        var duckToInfer = typeParameters.Zip(typeArguments).
                          ToDictionary(kv => kv.First.ToString(), kv => kv.Second.ToString());

        newNode = newNode.ReplaceNodes(
            newNode.DescendantNodes().OfType <TypeSyntax>(),
            (_, n) => duckToInfer.TryGetValue(n.ToString(), out var infer) ? ParseTypeName(infer).WithTriviaFrom(n) : n);

        var ogNodeStr = ogNode.ToString();

        newNodes.TryAdd(ogNodeStr, new List <CSharpSyntaxNode>());
        newNodes[ogNodeStr].Add(newNode);
        return(newName);
    }
예제 #3
0
        internal SyntaxList <ArrayRankSpecifierSyntax> ConvertArrayRankSpecifierSyntaxes(
            SyntaxList <VBSyntax.ArrayRankSpecifierSyntax> arrayRankSpecifierSyntaxs,
            ArgumentListSyntax nodeArrayBounds, bool withSizes = true)
        {
            var bounds = SyntaxFactory.List(arrayRankSpecifierSyntaxs.Select(r => (ArrayRankSpecifierSyntax)r.Accept(_nodesVisitor)));

            if (nodeArrayBounds != null)
            {
                var sizesSpecified = nodeArrayBounds.Arguments.Any(a => !a.IsOmitted);
                var rank           = nodeArrayBounds.Arguments.Count;
                if (!sizesSpecified)
                {
                    rank += 1;
                }

                var convertedArrayBounds = withSizes && sizesSpecified?ConvertArrayBounds(nodeArrayBounds)
                                               : Enumerable.Repeat(SyntaxFactory.OmittedArraySizeExpression(), rank);

                var arrayRankSpecifierSyntax = SyntaxFactory.ArrayRankSpecifier(
                    SyntaxFactory.SeparatedList(
                        convertedArrayBounds));
                bounds = bounds.Insert(0, arrayRankSpecifierSyntax);
            }

            return(bounds);
        }
예제 #4
0
        internal static ClassDeclarationSyntax ReorderClass(SemanticModel semanticModel, ClassDeclarationSyntax cls)
        {
            SyntaxList <MemberDeclarationSyntax> originalMembers = cls.Members;

            SortOrder?prevSortOrder = null;
            var       sortedMembers = originalMembers
                                      .Select(member => new
            {
                Member    = member,
                SortOrder = new SortOrder(member, semanticModel)
            })
                                      .OrderBy(member => member.SortOrder)
                                      .Select(member =>
            {
                var newTrivia = FormatNewlines(
                    member.Member.GetLeadingTrivia(),
                    member.SortOrder,
                    prevSortOrder);
                var updated   = member.Member.WithLeadingTrivia(newTrivia);
                prevSortOrder = member.SortOrder;
                return(updated);
            });

            ;

            return(cls.WithMembers(new SyntaxList <MemberDeclarationSyntax>(sortedMembers)));
        }
예제 #5
0
        private Doc PrintAttributeLists(
            SyntaxNode node,
            SyntaxList <AttributeListSyntax> attributeLists)
        {
            if (attributeLists.Count == 0)
            {
                return(Doc.Null);
            }

            var parts     = new Parts();
            var separator = node is TypeParameterSyntax ||
                            node is ParameterSyntax
                ? Line
                : HardLine;

            parts.Push(
                Join(
                    separator,
                    attributeLists.Select(this.PrintAttributeListSyntax)
                    )
                );

            if (!(node is ParameterSyntax))
            {
                parts.Push(separator);
            }

            return(Concat(parts));
        }
예제 #6
0
        public static async Task <Document> RefactorAsync(
            Document document,
            NamespaceDeclarationSyntax namespaceDeclaration,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            if (namespaceDeclaration == null)
            {
                throw new ArgumentNullException(nameof(namespaceDeclaration));
            }

            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var compilationUnit = (CompilationUnitSyntax)root;

            SyntaxList <UsingDirectiveSyntax> usings = namespaceDeclaration.Usings;

            CompilationUnitSyntax newCompilationUnit = compilationUnit
                                                       .RemoveNodes(usings, SyntaxRemoveOptions.KeepUnbalancedDirectives)
                                                       .AddUsings(
                keepSingleLineCommentsOnTop: true,
                usings: usings.Select(f => f.WithFormatterAnnotation()).ToArray());

            return(document.WithSyntaxRoot(newCompilationUnit));
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            NamespaceDeclarationSyntax namespaceDeclaration,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            var compilationUnit = (CompilationUnitSyntax)root;

            SyntaxList <UsingDirectiveSyntax> usings = namespaceDeclaration.Usings;

            UsingDirectiveSyntax[] newUsings = usings
                                               .Select(f => EnsureFullyQualifiedName(f, semanticModel, cancellationToken))
                                               .ToArray();

            newUsings[0] = newUsings[0].WithoutLeadingTrivia();
            newUsings[newUsings.Length - 1] = newUsings[newUsings.Length - 1].WithoutTrailingTrivia();

            CompilationUnitSyntax newCompilationUnit = compilationUnit
                                                       .RemoveNodes(usings, SyntaxRemoveOptions.KeepUnbalancedDirectives)
                                                       .AddUsings(
                keepSingleLineCommentsOnTop: true,
                usings: newUsings);

            return(document.WithSyntaxRoot(newCompilationUnit));
        }
예제 #8
0
        protected SyntaxList <ExpressionSyntax> RewritePostfixUnarys(SyntaxList <ExpressionSyntax> nodes)
        {
            if (nodes.Count == 0)
            {
                return(nodes);
            }

            return(Syntax.List(nodes.Select(RewritePostfixUnarys)));
        }
 private SyntaxList<UsingDirectiveSyntax> RemoveEmptyLines(SyntaxList<UsingDirectiveSyntax> finalUsings)
 {
     return SyntaxFactory.List(finalUsings.Select(u =>
     {
         var trivia = u.GetLeadingTrivia();
         if (trivia.Count > 0 && trivia.All((arg) => arg.Kind() == SyntaxKind.WhitespaceTrivia))
         {
             return u.WithLeadingTrivia(trivia.Where(t => t.Kind() != SyntaxKind.EndOfLineTrivia));
         }
         return u;
     }));
 }
예제 #10
0
        public static async Task <Document> RefactorAsync(
            Document document,
            NamespaceDeclarationSyntax namespaceDeclaration,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            if (namespaceDeclaration == null)
            {
                throw new ArgumentNullException(nameof(namespaceDeclaration));
            }

            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var compilationUnit = (CompilationUnitSyntax)root;

            SyntaxList <UsingDirectiveSyntax> usings = namespaceDeclaration.Usings;

            CompilationUnitSyntax newCompilationUnit = compilationUnit
                                                       .RemoveNodes(usings, SyntaxRemoveOptions.KeepUnbalancedDirectives);

            if (!compilationUnit.Usings.Any())
            {
                SyntaxTriviaList leadingTrivia = compilationUnit.GetLeadingTrivia();

                SyntaxTrivia[] topTrivia = GetTopSingleLineComments(leadingTrivia).ToArray();

                if (topTrivia.Length > 0)
                {
                    newCompilationUnit = newCompilationUnit.WithoutLeadingTrivia();

                    usings = usings.Replace(
                        usings.First(),
                        usings.First().WithLeadingTrivia(topTrivia));

                    usings = usings.Replace(
                        usings.Last(),
                        usings.Last().WithTrailingTrivia(leadingTrivia.Skip(topTrivia.Length)));
                }
            }

            newCompilationUnit = newCompilationUnit.AddUsings(usings.Select(f => f.WithFormatterAnnotation()));

            return(document.WithSyntaxRoot(newCompilationUnit));
        }
예제 #11
0
        public static Task <Document> RefactorAsync(
            Document document,
            UnsafeStatementSyntax unsafeStatement,
            SyntaxNode containingNode,
            CancellationToken cancellationToken)
        {
            SyntaxToken keyword = unsafeStatement.UnsafeKeyword;

            BlockSyntax block = unsafeStatement.Block;

            SyntaxList <StatementSyntax> statements = block.Statements;

            SyntaxNode newNode = null;

            int count = statements.Count;

            if (count == 0)
            {
                newNode = containingNode.RemoveNode(unsafeStatement);
            }
            else
            {
                StatementSyntax first = statements.First();
                StatementSyntax last  = statements.Last();

                SyntaxTriviaList leadingTrivia = keyword.LeadingTrivia
                                                 .AddRange(keyword.TrailingTrivia.EmptyIfWhitespace())
                                                 .AddRange(block.GetLeadingTrivia().EmptyIfWhitespace())
                                                 .AddRange(block.OpenBraceToken.TrailingTrivia.EmptyIfWhitespace())
                                                 .AddRange(first.GetLeadingTrivia().EmptyIfWhitespace());

                SyntaxTriviaList trailingTrivia = last.GetTrailingTrivia().EmptyIfWhitespace()
                                                  .AddRange(block.CloseBraceToken.LeadingTrivia.EmptyIfWhitespace())
                                                  .AddRange(block.GetTrailingTrivia());

                statements = statements
                             .ReplaceAt(0, first.WithLeadingTrivia(leadingTrivia))
                             .ReplaceAt(count - 1, last.WithTrailingTrivia(trailingTrivia));

                newNode = containingNode.ReplaceNode(unsafeStatement, statements.Select(f => f.WithFormatterAnnotation()));
            }

            newNode = newNode.InsertModifier(SyntaxKind.UnsafeKeyword);

            return(document.ReplaceNodeAsync(containingNode, newNode, cancellationToken));
        }
예제 #12
0
        public static Doc Print(SyntaxNode node, SyntaxList <AttributeListSyntax> attributeLists)
        {
            if (attributeLists.Count == 0)
            {
                return(Doc.Null);
            }

            var docs      = new List <Doc>();
            Doc separator = node is TypeParameterSyntax || node is ParameterSyntax
                ? Doc.Line
                : Doc.HardLine;

            docs.Add(Doc.Join(separator, attributeLists.Select(AttributeList.Print)));

            if (!(node is ParameterSyntax))
            {
                docs.Add(separator);
            }

            return(Doc.Concat(docs));
        }
        private static string Convert(
            SourceText text,
            SyntaxNode node,
            IDictionary <string, string> identifierMap,
            bool convertStrings)
        {
            if (node is CS.Syntax.StatementSyntax)
            {
                NodeVisitor      nodeVisitor      = new NodeVisitor(text, identifierMap, convertStrings);
                StatementVisitor statementVisitor = new StatementVisitor(nodeVisitor, text);
                SyntaxList <VB.Syntax.StatementSyntax> vbStatements = statementVisitor.Visit(node);

                return(string.Join(Environment.NewLine, vbStatements.Select(s => s.NormalizeWhitespace())));
            }
            else
            {
                NodeVisitor visitor = new NodeVisitor(text, identifierMap, convertStrings);
                SyntaxNode  vbNode  = visitor.Visit(node);

                return(vbNode.NormalizeWhitespace().ToFullString());
            }
        }
예제 #14
0
        private static SyntaxList <AttributeListSyntax> RemoveAttributeFromAttributeLists(
            SyntaxList <AttributeListSyntax> attributeLists,
            SyntaxNode attributeToRemove,
            CodeGenerationOptions options,
            out int positionOfRemovedNode,
            out SyntaxTriviaList triviaOfRemovedNode)
        {
            foreach (var attributeList in attributeLists)
            {
                var attributes = attributeList.Attributes;
                if (attributes.Contains(attributeToRemove))
                {
                    IEnumerable <SyntaxTrivia>        trivia;
                    IEnumerable <AttributeListSyntax> newAttributeLists;
                    if (attributes.Count == 1)
                    {
                        // Remove the entire attribute list.
                        ComputePositionAndTriviaForRemoveAttributeList(attributeList, (SyntaxTrivia t) => t.IsKind(SyntaxKind.EndOfLineTrivia), out positionOfRemovedNode, out trivia);
                        newAttributeLists = attributeLists.Where(aList => aList != attributeList);
                    }
                    else
                    {
                        // Remove just the given attribute from the attribute list.
                        ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, (SyntaxToken t) => t.IsKind(SyntaxKind.CommaToken), out positionOfRemovedNode, out trivia);
                        var newAttributes    = SyntaxFactory.SeparatedList(attributes.Where(a => a != attributeToRemove));
                        var newAttributeList = attributeList.WithAttributes(newAttributes);
                        newAttributeLists = attributeLists.Select(attrList => attrList == attributeList ? newAttributeList : attrList);
                    }

                    triviaOfRemovedNode = trivia.ToSyntaxTriviaList();
                    return(newAttributeLists.ToSyntaxList());
                }
            }

            throw new ArgumentException("attributeToRemove");
        }
예제 #15
0
        private static SyntaxList <AttributeListSyntax> SortAttributes(SyntaxList <AttributeListSyntax> attributeLists)
        {
            if (attributeLists.Count == 0)
            {
                return(attributeLists);
            }

            var sortedAttributeLists = new SyntaxList <AttributeListSyntax>();

            var firstLeadingTrivia  = attributeLists[0].GetLeadingTrivia();
            var secondLeadingTrivia = firstLeadingTrivia;

            if (attributeLists.Count > 1)
            {
                secondLeadingTrivia = attributeLists[1].GetLeadingTrivia();
            }

            var orderedAttributeLists = attributeLists.Select(q => q.WithLeadingTrivia(secondLeadingTrivia)).OrderBy(q => q.Attributes.ToString());

            sortedAttributeLists = sortedAttributeLists.AddRange(orderedAttributeLists);
            sortedAttributeLists = sortedAttributeLists.Replace(sortedAttributeLists[0], sortedAttributeLists[0].WithLeadingTrivia(firstLeadingTrivia));

            return(sortedAttributeLists);
        }
 private string GetNewText <TSyntax>(SyntaxList <TSyntax> organizedList)
     where TSyntax : SyntaxNode
 {
     return(string.Join(string.Empty, organizedList.Select(t => t.ToFullString())));
 }
 public int GetHashCode(SyntaxList <T> obj)
 {
     return((obj.Count + string.Join(", ", obj.Select(x => x.GetType().FullName).Distinct())).GetHashCode());
 }
 public static string ConvertSyntaxList <T>(this SyntaxList <T> source) where T : SyntaxNode
 {
     return(string.Join("", source.Select(BuilderStatic.SyntaxNode)));
 }
예제 #19
0
 private string Parse(SyntaxList <MemberDeclarationSyntax> members)
 {
     return(members.Select(ParseOne)
            .Where(s => !string.IsNullOrEmpty(s))
            .JoinToString("\n"));
 }
예제 #20
0
 private bool HasSqlNamespace(SyntaxList <UsingDirectiveSyntax> usings) =>
 usings.Select(usingDirective => usingDirective.Name)
 .Any(name => SqlNamespaces.Any(sn => SyntaxFactory.AreEquivalent(name, sn)));
예제 #21
0
 public static List <glsl.StatementSyntax> Translate(this SyntaxList <cs.StatementSyntax> node)
 {
     return(node.Select(n => Translate(n)).Cast <glsl.StatementSyntax>().ToList());
 }
예제 #22
0
 public static List <string> GetAttributeList(SyntaxList <AttributeListSyntax> attributeListSyntax)
 {
     return(attributeListSyntax.Select(als => als.Attributes.ToString()).ToList());
 }
예제 #23
0
 public SyntaxListTranslation(SyntaxList <T> syntaxList, SyntaxTranslation parent) : base(parent)
 {
     this.syntaxList  = syntaxList;
     this.Parent      = parent;
     SyntaxCollection = syntaxList.Select(f => f.Get <SyntaxTranslation>(this)).ToList();
 }
 protected override SyntaxNodeOrTokenList ToNodesOrTokens(SyntaxList <TElementNode> value) => SyntaxFactory.NodeOrTokenList(value.Select(n => (SyntaxNodeOrToken)n));
예제 #25
0
 private static List <string> GetUsings(SyntaxList <UsingDirectiveSyntax> usings)
 {
     return(usings.Select(u => u.ToString()).ToList());
 }