Exemplo n.º 1
0
        public SyntaxNode Replace(SyntaxNode root, SemanticModel model, Func <SyntaxNode, Tuple <SyntaxTree, SemanticModel> > updater, SharpSixRewriter rewriter)
        {
            var discards = root
                           .DescendantNodes()
                           .OfType <DiscardDesignationSyntax>();

            var outVars = root
                          .DescendantNodes()
                          .OfType <ArgumentSyntax>()
                          .Where(arg => arg.Expression is DeclarationExpressionSyntax && arg.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword);

            var outDiscardVars = root
                                 .DescendantNodes()
                                 .OfType <ArgumentSyntax>()
                                 .Where(arg => {
                if (arg.Expression is IdentifierNameSyntax ins && ins.Identifier.ValueText == DISCARD_IDENTIFIER)
                {
                    var si = model.GetSymbolInfo(arg.Expression);
                    return(si.Symbol == null || si.Symbol is IDiscardSymbol);
                }

                return(false);
            });

            var discardAssigments = root
                                    .DescendantNodes()
                                    .OfType <AssignmentExpressionSyntax>()
                                    .Where(assignment => {
                if (assignment.Left is IdentifierNameSyntax ins && ins.Identifier.ValueText == DISCARD_IDENTIFIER)
                {
                    var si = model.GetSymbolInfo(assignment.Left);
                    return(si.Symbol == null || si.Symbol is IDiscardSymbol);
                }

                return(false);
            });

            var updatedMembers = new Dictionary <MemberAccessExpressionSyntax, string>();

            foreach (var memberAccess in root.DescendantNodes().OfType <MemberAccessExpressionSyntax>())
            {
                try
                {
                    var symbol = model.GetSymbolInfo(memberAccess).Symbol;

                    if (symbol != null && symbol is IFieldSymbol && symbol.ContainingType.IsTupleType)
                    {
                        var field      = symbol as IFieldSymbol;
                        var tupleField = field.CorrespondingTupleField;
                        updatedMembers[memberAccess] = tupleField.Name;
                    }
                }
                catch (Exception E)
                {
                    Console.WriteLine(E);
                }
            }

            var updatedStatements  = new Dictionary <StatementSyntax, List <LocalDeclarationStatementSyntax> >();
            var updatedDiscards    = new Dictionary <DiscardDesignationSyntax, string>();
            var updatedDiscardVars = new Dictionary <ArgumentSyntax, string>();

            var tempIndex = 0;

            foreach (var discard in discards)
            {
                try
                {
                    var noLocal     = false;
                    var parentTuple = discard.GetParent <TupleExpressionSyntax>();
                    if (parentTuple != null && parentTuple.Parent is AssignmentExpressionSyntax ae && ae.Left == parentTuple)
                    {
                        noLocal = true;
                    }

                    var typeInfo        = model.GetTypeInfo(discard.Parent);
                    var beforeStatement = discard.Ancestors().OfType <StatementSyntax>().FirstOrDefault();

                    if (beforeStatement != null)
                    {
                        if (typeInfo.Type != null)
                        {
                            string instance = DISCARD_VARIABLE + ++tempIndex;
                            if (beforeStatement.Parent != null)
                            {
                                var info = LocalUsageGatherer.GatherInfo(model, beforeStatement.Parent);

                                while (info.DirectlyOrIndirectlyUsedLocals.Any(s => s.Name == instance) || info.Names.Contains(instance))
                                {
                                    instance = DISCARD_VARIABLE + ++tempIndex;
                                }
                            }

                            if (!noLocal)
                            {
                                var locals  = updatedStatements.ContainsKey(beforeStatement) ? updatedStatements[beforeStatement] : new List <LocalDeclarationStatementSyntax>();
                                var varDecl = SyntaxFactory.VariableDeclaration(SyntaxHelper.GenerateTypeSyntax(typeInfo.Type, model, discard.Parent.GetLocation().SourceSpan.Start, rewriter)).WithVariables(SyntaxFactory.SingletonSeparatedList(
                                                                                                                                                                                                                  SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(instance))
                                                                                                                                                                                                                  ));

                                var local = SyntaxFactory.LocalDeclarationStatement(varDecl).NormalizeWhitespace().WithTrailingTrivia(SyntaxFactory.Whitespace("\n"));
                                locals.Add(local);

                                updatedStatements[beforeStatement] = locals;
                            }

                            updatedDiscards[discard] = instance;
                        }
                        else if (discard.Parent is DeclarationPatternSyntax && !(discard.Parent.Parent is IsPatternExpressionSyntax))
                        {
                            string instance = DISCARD_VARIABLE + ++tempIndex;
                            if (beforeStatement.Parent != null)
                            {
                                var info = LocalUsageGatherer.GatherInfo(model, beforeStatement.Parent);

                                while (info.DirectlyOrIndirectlyUsedLocals.Any(s => s.Name == instance) || info.Names.Contains(instance))
                                {
                                    instance = DISCARD_VARIABLE + ++tempIndex;
                                }
                            }

                            updatedDiscards[discard] = instance;
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new ReplacerException(discard, e);
                }
            }

            foreach (var discardVar in outDiscardVars)
            {
                try
                {
                    var typeInfo = model.GetTypeInfo(discardVar.Expression);

                    if (typeInfo.Type != null)
                    {
                        var beforeStatement = discardVar.Ancestors().OfType <StatementSyntax>().FirstOrDefault();
                        if (beforeStatement != null)
                        {
                            string instance = DISCARD_VARIABLE + ++tempIndex;
                            if (beforeStatement.Parent != null)
                            {
                                var info = LocalUsageGatherer.GatherInfo(model, beforeStatement.Parent);

                                while (info.DirectlyOrIndirectlyUsedLocals.Any(s => s.Name == instance) || info.Names.Contains(instance))
                                {
                                    instance = DISCARD_VARIABLE + ++tempIndex;
                                }
                            }

                            var locals  = updatedStatements.ContainsKey(beforeStatement) ? updatedStatements[beforeStatement] : new List <LocalDeclarationStatementSyntax>();
                            var varDecl = SyntaxFactory.VariableDeclaration(SyntaxHelper.GenerateTypeSyntax(typeInfo.Type, model, discardVar.Expression.GetLocation().SourceSpan.Start, rewriter)).WithVariables(SyntaxFactory.SingletonSeparatedList(
                                                                                                                                                                                                                     SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(instance))
                                                                                                                                                                                                                     ));

                            var local = SyntaxFactory.LocalDeclarationStatement(varDecl).NormalizeWhitespace().WithTrailingTrivia(SyntaxFactory.Whitespace("\n"));
                            locals.Add(local);

                            updatedStatements[beforeStatement] = locals;
                            updatedDiscardVars[discardVar]     = instance;
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new ReplacerException(discardVar, e);
                }
            }

            foreach (var outVar in outVars)
            {
                try
                {
                    if (((DeclarationExpressionSyntax)outVar.Expression).Designation.Kind() == SyntaxKind.DiscardDesignation)
                    {
                        continue;
                    }

                    var typeInfo = model.GetTypeInfo(outVar.Expression);

                    if (typeInfo.Type != null)
                    {
                        var beforeStatement = outVar.Ancestors().OfType <StatementSyntax>().FirstOrDefault();
                        if (beforeStatement != null)
                        {
                            if (outVar.Expression is DeclarationExpressionSyntax de)
                            {
                                if (de.Designation is SingleVariableDesignationSyntax designation)
                                {
                                    var locals  = updatedStatements.ContainsKey(beforeStatement) ? updatedStatements[beforeStatement] : new List <LocalDeclarationStatementSyntax>();
                                    var varDecl = SyntaxFactory.VariableDeclaration(SyntaxHelper.GenerateTypeSyntax(typeInfo.Type, model, outVar.Expression.GetLocation().SourceSpan.Start, rewriter)).WithVariables(SyntaxFactory.SingletonSeparatedList(
                                                                                                                                                                                                                         SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(designation.Identifier.ValueText))
                                                                                                                                                                                                                         ));

                                    locals.Add(SyntaxFactory.LocalDeclarationStatement(varDecl).NormalizeWhitespace().WithTrailingTrivia(SyntaxFactory.Whitespace("\n")));

                                    updatedStatements[beforeStatement] = locals;
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new ReplacerException(outVar, e);
                }
            }

            var annotatedStatemnts   = new Dictionary <SyntaxAnnotation, List <LocalDeclarationStatementSyntax> >();
            var annotatedDiscards    = new Dictionary <SyntaxAnnotation, string>();
            var annotatedDiscardVars = new Dictionary <SyntaxAnnotation, string>();
            var annotatedAssigments  = new List <SyntaxAnnotation>();
            var annotatedMembers     = new Dictionary <SyntaxAnnotation, string>();

            var keys = updatedStatements.Keys.Cast <SyntaxNode>()
                       .Concat(updatedDiscards.Keys.Cast <SyntaxNode>())
                       .Concat(updatedDiscardVars.Keys.Cast <SyntaxNode>())
                       .Concat(discardAssigments)
                       .Concat(updatedMembers.Keys.Cast <SyntaxNode>());

            root = root.ReplaceNodes(keys, (n1, n2) =>
            {
                var annotation = new SyntaxAnnotation();

                if (n1 is AssignmentExpressionSyntax)
                {
                    annotatedAssigments.Add(annotation);
                }
                else if (n1 is DiscardDesignationSyntax)
                {
                    annotatedDiscards[annotation] = updatedDiscards[(DiscardDesignationSyntax)n1];
                }
                else if (n1 is ArgumentSyntax)
                {
                    annotatedDiscardVars[annotation] = updatedDiscardVars[(ArgumentSyntax)n1];
                }
                else if (n1 is MemberAccessExpressionSyntax)
                {
                    annotatedMembers[annotation] = updatedMembers[(MemberAccessExpressionSyntax)n1];
                }
                else
                {
                    annotatedStatemnts[annotation] = updatedStatements[(StatementSyntax)n1];
                }

                n2 = n2.WithAdditionalAnnotations(annotation);
                return(n2);
            });

            foreach (var annotation in annotatedDiscards.Keys)
            {
                var annotatedNode = root.GetAnnotatedNodes(annotation).First();
                var name          = annotatedDiscards[annotation];

                root = root.ReplaceNode(annotatedNode, SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier(name)).NormalizeWhitespace());
            }

            foreach (var annotation in annotatedDiscardVars.Keys)
            {
                var annotatedNode = root.GetAnnotatedNodes(annotation).First();
                var name          = annotatedDiscardVars[annotation];

                root = root.ReplaceNode(annotatedNode, ((ArgumentSyntax)annotatedNode).WithExpression(SyntaxFactory.IdentifierName(name)));
            }

            foreach (var annotation in annotatedAssigments)
            {
                var annotatedNode = root.GetAnnotatedNodes(annotation).First();
                root = root.ReplaceNode(annotatedNode, ((AssignmentExpressionSyntax)annotatedNode).WithLeft(SyntaxFactory.IdentifierName("H5.Script.Discard")));
            }

            outVars = root
                      .DescendantNodes()
                      .OfType <ArgumentSyntax>()
                      .Where(arg => arg.Expression is DeclarationExpressionSyntax && arg.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword);

            root = root.ReplaceNodes(outVars, (n1, n2) =>
            {
                if (!(((DeclarationExpressionSyntax)n2.Expression).Designation is SingleVariableDesignationSyntax designation))
                {
                    return(n2);
                }

                return(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(designation.Identifier)).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.OutKeyword)).WithRefOrOutKeyword(SyntaxFactory.Token(SyntaxKind.OutKeyword)).NormalizeWhitespace());
            });
Exemplo n.º 2
0
        public SyntaxNode ReplaceForeachDeconstructions(SyntaxNode root, SemanticModel model)
        {
            var loops = root
                        .DescendantNodes()
                        .OfType <ForEachVariableStatementSyntax>()
                        .Where(forEach => forEach.Variable is TupleExpressionSyntax || forEach.Variable is DeclarationExpressionSyntax de && de.Designation is ParenthesizedVariableDesignationSyntax);

            if (loops.Any())
            {
                Dictionary <ForEachVariableStatementSyntax, DeconstructionInfo> infos = new Dictionary <ForEachVariableStatementSyntax, DeconstructionInfo>();

                foreach (var loop in loops)
                {
                    try
                    {
                        var deconstructionInfo = model.GetDeconstructionInfo(loop);
                        infos.Add(loop, deconstructionInfo);
                    }
                    catch (Exception e)
                    {
                        throw new ReplacerException(loop, e);
                    }
                }

                var tempIndex = 0;
                root = root.ReplaceNodes(loops, (n1, n2) => {
                    var variable = n2.Variable;

                    string instance = "_d" + ++tempIndex;
                    if (n1.Parent != null)
                    {
                        var info = LocalUsageGatherer.GatherInfo(model, n1.Parent);

                        while (info.DirectlyOrIndirectlyUsedLocals.Any(s => s.Name == instance) || info.Names.Contains(instance))
                        {
                            instance = "_d" + ++tempIndex;
                        }
                    }

                    var newloop = SyntaxFactory.ForEachStatement(SyntaxFactory.IdentifierName("var"), SyntaxFactory.Identifier(instance), n2.Expression, n2.Statement)
                                  .WithLeadingTrivia(n2.GetLeadingTrivia())
                                  .WithTrailingTrivia(n2.GetTrailingTrivia());

                    var deconstructionInfo = infos[n1];
                    var invocation         = DeconstructionToMethod(model, variable, SyntaxFactory.IdentifierName(instance), deconstructionInfo);

                    if (newloop.Statement is BlockSyntax b)
                    {
                        foreach (var statement in b.Statements)
                        {
                            try
                            {
                                if (statement.ContainsAnnotations)
                                {
                                    var annotaions = statement.GetAnnotations("last_variable");
                                    if (annotaions != null && annotaions.Any())
                                    {
                                        newloop = newloop.InsertNodesAfter(statement, new[] { SyntaxFactory.ExpressionStatement(invocation) });
                                        break;
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                throw new ReplacerException(statement, e);
                            }
                        }
                    }

                    return(newloop.NormalizeWhitespace().WithTrailingTrivia(SyntaxFactory.Whitespace("\n")));
                });
            }

            return(root);
        }