Beispiel #1
0
        private static TNode ReplaceReferencesToParameterWithValue <TNode>(SemanticModel semanticModel, IParameterSymbol parameter, TNode node)
            where TNode : SyntaxNode
        {
            var rewriter = new Rewriter(semanticModel, parameter);

            return((TNode)rewriter.Visit(node));
        }
        protected override SyntaxNode Rewrite(
            ExternAliasDirectiveSyntax[] externAliases,
            UsingDirectiveSyntax[] usingDirectives,
            UsingDirectiveSyntax[] staticUsingDirectives,
            UsingDirectiveSyntax[] aliasDirectives,
            SyntaxNode externContainer,
            SyntaxNode usingContainer,
            SyntaxNode staticUsingContainer,
            SyntaxNode aliasContainer,
            bool placeSystemNamespaceFirst,
            bool allowInHiddenRegions,
            SyntaxNode root,
            CancellationToken cancellationToken
            )
        {
            var rewriter = new Rewriter(
                externAliases,
                usingDirectives,
                staticUsingDirectives,
                aliasDirectives,
                externContainer,
                usingContainer,
                staticUsingContainer,
                aliasContainer,
                placeSystemNamespaceFirst,
                allowInHiddenRegions,
                cancellationToken
                );

            var newRoot = rewriter.Visit(root);

            return(newRoot);
        }
Beispiel #3
0
        private static CSharpSyntaxTree EditSyntaxTree(CSharpSyntaxTree syntaxTree, CSharpCompilation compilation, CancellationToken cancellationToken)
        {
            Rewriter         rewriter = new Rewriter(compilation, syntaxTree, cancellationToken);
            CSharpSyntaxNode root     = syntaxTree.GetRoot(cancellationToken);

            return(syntaxTree.WithRoot(rewriter.Visit(root)) as CSharpSyntaxTree);
        }
Beispiel #4
0
 protected override TNode RewriteCore <TNode>(
     TNode node,
     SyntaxNode replacementNode,
     ISet <ExpressionSyntax> matches)
 {
     return((TNode)Rewriter.Visit(node, replacementNode, matches));
 }
Beispiel #5
0
        public static RazorSyntaxTree Rewrite(RazorSyntaxTree syntaxTree, string tagHelperPrefix, IEnumerable <TagHelperDescriptor> descriptors)
        {
            var errorSink = new ErrorSink();

            syntaxTree = MarkupElementRewriter.AddMarkupElements(syntaxTree);

            var rewriter = new Rewriter(
                syntaxTree.Source,
                tagHelperPrefix,
                descriptors,
                syntaxTree.Options.FeatureFlags,
                errorSink);

            var rewritten = rewriter.Visit(syntaxTree.Root);

            var errorList = new List <RazorDiagnostic>();

            errorList.AddRange(errorSink.Errors);
            errorList.AddRange(descriptors.SelectMany(d => d.GetAllDiagnostics()));

            var diagnostics = CombineErrors(syntaxTree.Diagnostics, errorList).OrderBy(error => error.Span.AbsoluteIndex);

            var newSyntaxTree = RazorSyntaxTree.Create(rewritten, syntaxTree.Source, diagnostics, syntaxTree.Options);

            newSyntaxTree = MarkupElementRewriter.RemoveMarkupElements(newSyntaxTree);

            return(newSyntaxTree);
        }
        protected override SyntaxNode Rewrite(
            SemanticModel semanticModel, SyntaxNode root, ISet <MemberAccessExpressionSyntax> memberAccessNodes)
        {
            var rewriter = new Rewriter(memberAccessNodes);

            return(rewriter.Visit(root));
        }
        public async Task<Document> OrganizeImportsAsync(Document document, bool placeSystemNamespaceFirst, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var rewriter = new Rewriter(placeSystemNamespaceFirst);
            var newRoot = rewriter.Visit(root);

            return document.WithSyntaxRoot(newRoot);
        }
Beispiel #8
0
        protected override async Task <Document> ProcessAsync(Document document, IEnumerable <ISyntaxOrganizer> organizers, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var rewriter = new Rewriter(this, organizers, await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false), cancellationToken);

            return(document.WithSyntaxRoot(rewriter.Visit(root)));
        }
Beispiel #9
0
        public async Task <Document> OrganizeImportsAsync(Document document, bool placeSystemNamespaceFirst, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var rewriter = new Rewriter(placeSystemNamespaceFirst);
            var newRoot  = rewriter.Visit(root);

            return(document.WithSyntaxRoot(newRoot));
        }
Beispiel #10
0
        public async Task <Document> OrganizeImportsAsync(Document document, OrganizeImportsOptions options, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var rewriter = new Rewriter(options);
            var newRoot  = rewriter.Visit(root);

            return(document.WithSyntaxRoot(newRoot));
        }
        public string ClearSourceText(string sourceText, OffsetsStore offsetsStore)
        {
            var tree = ParseText(sourceText);
            var root = tree.GetRoot();

            var rewriter = new Rewriter(offsetsStore);
            var result   = rewriter.Visit(root);

            return(result.ToFullString().ToLowerInvariant());
        }
Beispiel #12
0
        protected override async Task <Solution> ProcessAsync(
            Document document,
            SyntaxNode syntaxRoot,
            CancellationToken cancellationToken)
        {
            var rewriter = new Rewriter(await document.GetSemanticModelAsync(cancellationToken));
            var newNode  = rewriter.Visit(syntaxRoot);

            return(document.Project.Solution.WithDocumentSyntaxRoot(document.Id, newNode));
        }
Beispiel #13
0
        private async Task <Document> SimplifyAllLambdasAsync(
            Document document,
            CancellationToken cancellationToken)
        {
            var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            var rewriter = new Rewriter(this, semanticDocument, n => true, cancellationToken);
            var result   = rewriter.Visit(semanticDocument.Root);

            return(document.WithSyntaxRoot(result));
        }
        private static async Task <Document> SimplifyLambdaAsync(
            Document document,
            SyntaxNode lambda,
            CancellationToken cancellationToken)
        {
            var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            var rewriter = new Rewriter(semanticDocument, n => n == lambda, cancellationToken);
            var result   = rewriter.Visit(semanticDocument.Root);

            return(document.WithSyntaxRoot(result));
        }
    private CSharpSyntaxTree EditSyntaxTree(CSharpSyntaxTree tree, CSharpCompilation compilation, CancellationToken token)
    {
        // The whole compilation is edited at once instead of going through each node independently,
        // because syntax trees cannot change if we want to use their semantic model.

        SemanticModel semanticModel = compilation.GetSemanticModel(tree, true);
        SyntaxNode    root          = tree.GetRoot(token);

        Rewriter rewriter = new Rewriter(semanticModel, startAtSyntax);

        return((CSharpSyntaxTree)tree.WithRoot(rewriter.Visit(root)));
    }
Beispiel #16
0
        public override SyntaxNode CleanUp(SyntaxNode initialSourceNode)
        {
            orginalDocument = ProjectItemDetails.ProjectItemDocument;
            WorkingDocument = ProjectItemDetails.ProjectItemDocument;

            var walker = new MyWalker(ProjectItemDetails, Options);

            walker.Visit(initialSourceNode);

            if (walker.VariablesToRemove.Any())
            {
                var rewriter = new Rewriter(walker, ProjectItemDetails, Options);
                initialSourceNode = rewriter.Visit(initialSourceNode);
                WorkingDocument   = WorkingDocument.WithSyntaxRoot(initialSourceNode);

                IEnumerable <SyntaxNode> annotations;

                do
                {
                    annotations = initialSourceNode.GetAnnotatedNodes(SELECTED_METHOD_ANNOTATION_RENAME);

                    if (annotations.Any() == false)
                    {
                        break;
                    }

                    var firstAnnotatedItem             = annotations.First();
                    var annotationOfFirstAnnotatedItem = firstAnnotatedItem.GetAnnotations(SELECTED_METHOD_ANNOTATION_RENAME).FirstOrDefault();

                    var renameResult = Renamer.RenameSymbol(WorkingDocument, initialSourceNode, null, firstAnnotatedItem, annotationOfFirstAnnotatedItem.Data);

                    WorkingDocument   = renameResult.Document;
                    initialSourceNode = WorkingDocument.GetSyntaxRootAsync().Result;

                    firstAnnotatedItem = initialSourceNode.GetAnnotatedNodes(annotationOfFirstAnnotatedItem).FirstOrDefault();
                    initialSourceNode  = initialSourceNode.ReplaceNode(firstAnnotatedItem, firstAnnotatedItem.WithoutAnnotations(SELECTED_METHOD_ANNOTATION_RENAME));

                    WorkingDocument   = WorkingDocument.WithSyntaxRoot(initialSourceNode);
                    initialSourceNode = WorkingDocument.GetSyntaxRootAsync().Result;
                }while (annotations.Any());

                initialSourceNode = initialSourceNode.RemoveNodes(initialSourceNode.GetAnnotatedNodes(SELECTED_METHOD_ANNOTATION_REMOVE), SyntaxRemoveOptions.KeepEndOfLine);
                var t = initialSourceNode.DescendantNodes().OfType <FieldDeclarationSyntax>().Where(x => x.Declaration.Variables.Count == 0);
                initialSourceNode = initialSourceNode.RemoveNodes(t, SyntaxRemoveOptions.KeepEndOfLine);

                WorkingDocument = WorkingDocument.WithSyntaxRoot(initialSourceNode);

                return(null);
            }

            return(initialSourceNode);
        }
Beispiel #17
0
        public override async Task <SyntaxNode> CleanUpAsync(SyntaxNode initialSourceNode)
        {
            var rewriter           = new Rewriter(ProjectItemDetails, IsReportOnlyMode, Options);
            var modifiedSourceNode = rewriter.Visit(initialSourceNode);

            if (IsReportOnlyMode)
            {
                CollectMessages(rewriter.GetReport());
                return(initialSourceNode);
            }

            return(modifiedSourceNode);
        }
        SyntaxNode RemoveAttributeKeyworkHelper(SyntaxNode initialSourceNode, SemanticModel semanticModel)
        {
            var syntaxRewriter     = new Rewriter(semanticModel, IsReportOnlyMode, Options);
            var modifiedSyntaxNode = syntaxRewriter.Visit(initialSourceNode);

            if (IsReportOnlyMode)
            {
                CollectMessages(syntaxRewriter.GetReport());
                return(initialSourceNode);
            }

            return(modifiedSyntaxNode);
        }
        public SyntaxNode SimplifyClassFieldDeclarationsHelper(SyntaxNode initialSourceNode, bool isReportOnlyMode, ICleanupOption options)
        {
            var rewriter           = new Rewriter(isReportOnlyMode, options);
            var modifiedSourceNode = rewriter.Visit(initialSourceNode);

            if (isReportOnlyMode)
            {
                CollectMessages(rewriter.GetReport());
                return(initialSourceNode);
            }

            return(modifiedSourceNode);
        }
Beispiel #20
0
        public SyntaxNode ConvertMembersToExpressionBodiedHelper(SyntaxNode initialSourceNode, ICleanupOption options)
        {
            var rewriter           = new Rewriter(IsReportOnlyMode, options);
            var modifiedSourceNode = rewriter.Visit(initialSourceNode);

            if (IsReportOnlyMode)
            {
                CollectMessages(rewriter.GetReport());
                return(initialSourceNode);
            }

            return(modifiedSourceNode);
        }
Beispiel #21
0
        public async Task <Document> OrganizeImportsAsync(Document document, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);

            var placeSystemNamespaceFirst = options.GetOption(GenerationOptions.PlaceSystemNamespaceFirst);
            var blankLineBetweenGroups    = options.GetOption(GenerationOptions.SeparateImportDirectiveGroups);

            var rewriter = new Rewriter(placeSystemNamespaceFirst, blankLineBetweenGroups);
            var newRoot  = rewriter.Visit(root);

            return(document.WithSyntaxRoot(newRoot));
        }
Beispiel #22
0
        public override async Task <SyntaxNode> CleanUpAsync(SyntaxNode initialSourceNode)
        {
            var rewriter           = new Rewriter(IsReportOnlyMode, Options);
            var modifiedSourceNode = rewriter.Visit(initialSourceNode);

            if (IsReportOnlyMode)
            {
                CollectMessages(rewriter.GetReport());
                return(initialSourceNode);
            }

            return(modifiedSourceNode);
            // return SimplyAsyncCallsHelper2(initialSourceNode);
        }
Beispiel #23
0
        static void Main(string[] args)
        {
            var file = args[0];
            var attributeTypeName = args[1];
            var attributeValue    = args[2];
            var tree     = CSharpSyntaxTree.ParseText(File.ReadAllText(file));
            var rewriter = new Rewriter(attributeTypeName, attributeValue);

            var newTree = tree.WithRootAndOptions(rewriter.Visit(tree.GetRoot()), CSharpParseOptions.Default);
            var s       = newTree.GetText().ToString();

            File.WriteAllText(file, s);
            Console.WriteLine($"Successfully updated the value of '{attributeTypeName}' to '{attributeValue}'");
        }
Beispiel #24
0
        private async Task <Document> MoveDeclarationNearReferenceAsync(Document document, State state, CancellationToken cancellationToken)
        {
            var innermostStatements =
                state.InnermostBlock.Statements.Where(s => s != state.DeclarationStatement).ToList();
            var innermostAffectedIndex = innermostStatements.IndexOf(state.FirstStatementAffectedInInnermostBlock);

            var crossesMeaningfulBlock = CrossesMeaningfulBlock(state);
            var warningAnnotation      = crossesMeaningfulBlock
                ? WarningAnnotation.Create(CSharpFeaturesResources.Warning_colon_Declaration_changes_scope_and_may_change_meaning)
                : null;

            var canMergeDeclarationAndAssignment = await CanMergeDeclarationAndAssignmentAsync(document, state, cancellationToken).ConfigureAwait(false);

            if (canMergeDeclarationAndAssignment)
            {
                // Replace the first reference with a new declaration.
                var declarationStatement = CreateMergedDeclarationStatement(state, state.FirstStatementAffectedInInnermostBlock);
                declarationStatement = warningAnnotation == null
                    ? declarationStatement
                    : declarationStatement.WithAdditionalAnnotations(warningAnnotation);

                innermostStatements[innermostAffectedIndex] = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation);
            }
            else
            {
                // If we're not merging with an existing declaration, make the declaration semantically
                // explicit to improve the chances that it won't break code.
                var explicitDeclarationStatement = await Simplifier.ExpandAsync(state.DeclarationStatement, document, cancellationToken : cancellationToken).ConfigureAwait(false);

                // place the declaration above the first statement that references it.
                var declarationStatement = warningAnnotation == null
                    ? explicitDeclarationStatement
                    : explicitDeclarationStatement.WithAdditionalAnnotations(warningAnnotation);

                innermostStatements.Insert(innermostAffectedIndex, declarationStatement.WithAdditionalAnnotations(Formatter.Annotation));
            }

            var newInnermostBlock = state.InnermostBlock.WithStatements(
                SyntaxFactory.List <StatementSyntax>(innermostStatements)).WithAdditionalAnnotations(Formatter.Annotation);

            var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

            var rewriter = new Rewriter(state.InnermostBlock, newInnermostBlock, state.OutermostBlock, state.DeclarationStatement);
            var newRoot  = rewriter.Visit(tree.GetRoot(cancellationToken));

            return(document.WithSyntaxRoot(newRoot));
        }
Beispiel #25
0
            public static IEnumerable <MutationResult> GetAllCombinations(SyntaxNode node, Mutatations original, Mutatations mutateTo)
            {
                List <MutationResult> results = new List <MutationResult>();
                int        i           = 0;
                Rewriter   rewriter    = new Rewriter(i, original, mutateTo);
                SyntaxNode visitedNode = rewriter.Visit(SyntaxNodeTools.CloneNode(node));

                results.Add(new MutationResult(rewriter.ChangeNote, visitedNode.ToString()));
                while (rewriter.changeMade)
                {
                    rewriter    = new Rewriter(++i, original, mutateTo);
                    visitedNode = rewriter.Visit(SyntaxNodeTools.CloneNode(node));
                    results.Add(new MutationResult(rewriter.ChangeNote, visitedNode.ToString()));
                }
                results.RemoveAt(results.Count - 1);
                return(results);
            }
Beispiel #26
0
    protected override void ExecuteCore(RazorCodeDocument codeDocument, DocumentIntermediateNode documentNode)
    {
        if (!IsComponentDocument(documentNode))
        {
            return;
        }

        if (documentNode.Options.DesignTime)
        {
            // Nothing to do during design time.
            return;
        }

        var rewriter = new Rewriter();

        rewriter.Visit(documentNode);
    }
        public override async Task <SyntaxNode> CleanUpAsync(SyntaxNode initialSourceNode)
        {
            var syntaxRewriter     = new Rewriter(initialSourceNode, IsReportOnlyMode, Options);
            var modifiedSourceNode = syntaxRewriter.Visit(initialSourceNode);

            if (IsReportOnlyMode)
            {
                CollectMessages(syntaxRewriter.GetReport());
                return(initialSourceNode);
            }

            if (modifiedSourceNode != initialSourceNode && TidyCSharpPackage.Instance != null)
            {
                initialSourceNode = Formatter.Format(modifiedSourceNode, TidyCSharpPackage.Instance.CleanupWorkingSolution.Workspace);
            }

            return(initialSourceNode);
        }
Beispiel #28
0
        protected override SyntaxNode Rewrite(
            ExternAliasDirectiveSyntax[] externAliases,
            UsingDirectiveSyntax[] usingDirectives,
            UsingDirectiveSyntax[] aliasDirectives,
            SyntaxNode externContainer,
            SyntaxNode usingContainer,
            SyntaxNode aliasContainer,
            bool placeSystemNamespaceFirst,
            SyntaxNode root)
        {
            var rewriter = new Rewriter(
                externAliases, usingDirectives, aliasDirectives,
                externContainer, usingContainer, aliasContainer,
                placeSystemNamespaceFirst);

            var newRoot = rewriter.Visit(root);

            return(newRoot);
        }
Beispiel #29
0
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync().ConfigureAwait(false);

            var    node  = root.FindNode(context.Span);
            string title = nameof(Resources.PX1001Fix).GetLocalized().ToString();

            if (node != null)
            {
                var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);

                context.RegisterCodeFix(CodeAction.Create(title, c =>
                {
                    var rewriter = new Rewriter(new PXContext(semanticModel.Compilation), context.Document, semanticModel);
                    var newNode  = rewriter.Visit(node);
                    return(Task.FromResult(context.Document.WithSyntaxRoot(root.ReplaceNode(node, newNode))));
                }, title),
                                        context.Diagnostics);
            }
        }
Beispiel #30
0
        public override async Task <Document> AddAsync(
            bool placeSystemNamespaceFirst,
            CodeGenerationOptions options,
            CancellationToken cancellationToken)
        {
            var importsContainerToMissingNamespaces = await DetermineNamespaceToImportAsync(
                options, cancellationToken).ConfigureAwait(false);

            if (importsContainerToMissingNamespaces.Count == 0)
            {
                return(this.Document);
            }

            var root = await this.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var rewriter = new Rewriter(this.Document, importsContainerToMissingNamespaces, options.PlaceSystemNamespaceFirst, cancellationToken);
            var newRoot  = rewriter.Visit(root);

            return(this.Document.WithSyntaxRoot(newRoot));
        }
        protected override SyntaxNode Rewrite(
            ExternAliasDirectiveSyntax[] externAliases,
            UsingDirectiveSyntax[] usingDirectives,
            UsingDirectiveSyntax[] staticUsingDirectives,
            UsingDirectiveSyntax[] aliasDirectives,
            SyntaxNode externContainer,
            SyntaxNode usingContainer,
            SyntaxNode staticUsingContainer,
            SyntaxNode aliasContainer,
            AddImportPlacementOptions options,
            SyntaxNode root,
            CancellationToken cancellationToken)
        {
            var rewriter = new Rewriter(
                externAliases, usingDirectives, staticUsingDirectives, aliasDirectives,
                externContainer, usingContainer, staticUsingContainer, aliasContainer,
                options, cancellationToken);

            var newRoot = rewriter.Visit(root);

            return(newRoot);
        }
        public override async Task<Document> AddAsync(
            IEnumerable<ISymbol> members,
            bool placeSystemNamespaceFirst,
            CodeGenerationOptions options,
            CancellationToken cancellationToken)
        {
            var importsContainerToMissingNamespaces = await DetermineNamespaceToImportAsync(members, options, cancellationToken).ConfigureAwait(false);
            if (importsContainerToMissingNamespaces.Count == 0)
            {
                return this.Document;
            }

            var root = await this.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var rewriter = new Rewriter(this.Document, importsContainerToMissingNamespaces, options.PlaceSystemNamespaceFirst, cancellationToken);
            var newRoot = rewriter.Visit(root);

            return this.Document.WithSyntaxRoot(newRoot);
        }
        protected override async Task<Solution> ProcessAsync(
            Document document,
            SyntaxNode syntaxRoot,
            CancellationToken cancellationToken)
        {
            var rewriter = new Rewriter(await document.GetSemanticModelAsync(cancellationToken));
            var newNode = rewriter.Visit(syntaxRoot);

            return document.Project.Solution.WithDocumentSyntaxRoot(document.Id, newNode);
        }
 protected override async Task<Document> ProcessAsync(Document document, IEnumerable<ISyntaxOrganizer> organizers, CancellationToken cancellationToken)
 {
     var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
     var rewriter = new Rewriter(this, organizers, await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false), cancellationToken);
     return document.WithSyntaxRoot(rewriter.Visit(root));
 }
Beispiel #35
0
        private static void MikesArchitecture(AssemblyResolver resolver, AssemblyNode assemblyNode,
            ContractNodes contractNodes, ContractNodes backupContracts)
        {
#if false
      var originalsourceDir = Path.GetDirectoryName(assemblyNode.Location);
      int oldPeVerifyCode = options.verify ? PEVerify(assemblyNode.Location, originalsourceDir) : -1;
#endif

            // Check to see if the assembly has already been rewritten

            if (!options.passthrough)
            {
                if (ContractNodes.IsAlreadyRewritten(assemblyNode))
                {
                    if (!options.allowRewritten)
                    {
                        Console.WriteLine("Assembly '" + assemblyNode.Name +
                                          "' has already been rewritten. I, your poor humble servant, cannot rewrite it. Instead I must give up without rewriting it. Help!");
                    }

                    return;
                }
            }

            // Extract the contracts from the code (includes checking the contracts)
            
            string contractFileName = Path.GetFileNameWithoutExtension(assemblyNode.Location) + ".Contracts";

            if (options.contracts == null || options.contracts.Count <= 0) contractFileName = null;

            if (options.contracts != null &&
                !options.contracts.Exists(name => name.Equals(assemblyNode.Name + ".Contracts.dll", StringComparison.OrdinalIgnoreCase)))
            {
                contractFileName = null;
            }

            AssemblyNode contractAssembly = null;
            if (contractFileName != null)
            {
                contractAssembly = resolver.ProbeForAssembly(contractFileName, assemblyNode.Directory,
                    resolver.DllExt);
            }

            if (!options.passthrough)
            {
                ContractNodes usedContractNodes;

                Extractor.ExtractContracts(assemblyNode, contractAssembly, contractNodes, backupContracts, contractNodes,
                    out usedContractNodes, options.EmitError, false);

                // important to extract source before we perform any more traversals due to contract instantiation. Otherwise,
                // we might get copies of contracts due to instantiation that have no source text yet.

                // Extract the text from the sources (optional)

                if (usedContractNodes != null && options.extractSourceText)
                {
                    GenerateDocumentationFromPDB gd = new GenerateDocumentationFromPDB(contractNodes);
                    gd.VisitForDoc(assemblyNode);
                }

                // After all contracts have been extracted in assembly, do some post-extractor checks

                // we run these even if no contracts were extracted due to checks having to do with overrides
                var contractNodesForChecks = usedContractNodes != null ? usedContractNodes : contractNodes;
                if (contractNodesForChecks != null)
                {
                    PostExtractorChecker pec = new PostExtractorChecker(contractNodesForChecks, options.EmitError, false,
                        options.fSharp, options.IsLegacyModeAssembly, options.addInterfaceWrappersWhenNeeded,
                        options.level);

                    if (contractAssembly != null)
                    {
                        pec.VisitForPostCheck(contractAssembly);
                    }
                    else
                    {
                        pec.VisitForPostCheck(assemblyNode);
                    }
                }

                // don't really need to test, since if they are the same, the assignment doesn't change that
                // but this is to emphasize that the nodes used in the AST by the extractor are different
                // than what we thought we were using.

                if (options.GetErrorCount() > 0)
                {
                    // we are done.
                    // But first, report any metadata errors so they are not masked by the errors
                    CheckForMetaDataErrors(assemblyNode);
                    return;
                }
            }

            // If we have metadata errors, cop out

            {
#if false
          for (int i = 0; i < assemblyNode.ModuleReferences.Count; i++)
          {
            Module m = assemblyNode.ModuleReferences[i].Module;
            Console.WriteLine("Location for referenced module '{0}' is '{1}'", m.Name, m.Location);
          }
#endif
                if (CheckForMetaDataErrors(assemblyNode))
                {
                    throw new Exception("Rewrite aborted due to metadata errors. Check output window");
                }
                for (int i = 0; i < assemblyNode.AssemblyReferences.Count; i++)
                {
                    AssemblyNode aref = assemblyNode.AssemblyReferences[i].Assembly;
                    if (CheckForMetaDataErrors(aref))
                    {
                        throw new Exception("Rewrite aborted due to metadata errors. Check output window");
                    }
                }
            }

            // Inject the contracts into the code (optional)

            if (options.rewrite && !options.passthrough)
            {
                // Rewrite the assembly in memory.
                ContractNodes cnForRuntime = null;

                // make sure to use the correct contract nodes for runtime code generation. We may have Contractnodes pointing to microsoft.Contracts even though
                // the code relies on mscorlib to provide the contracts. So make sure the code references the contract nodes first.
                if (contractNodes != null && contractNodes.ContractClass != null &&
                    contractNodes.ContractClass.DeclaringModule != SystemTypes.SystemAssembly)
                {
                    string assemblyNameContainingContracts = contractNodes.ContractClass.DeclaringModule.Name;
                    for (int i = 0; i < assemblyNode.AssemblyReferences.Count; i++)
                    {
                        if (assemblyNode.AssemblyReferences[i].Name == assemblyNameContainingContracts)
                        {
                            cnForRuntime = contractNodes;
                            break; // runtime actually references the contract library
                        }
                    }
                }

                if (cnForRuntime == null)
                {
                    // try to grab the system assembly contracts
                    cnForRuntime = ContractNodes.GetContractNodes(SystemTypes.SystemAssembly, null);
                }

                if (cnForRuntime == null)
                {
                    // Can happen if the assembly does not use contracts directly, but inherits them from some other place
                    // Use the normal contractNodes in this case (actually we should generate whatever we grab from ContractNodes)
                    cnForRuntime = contractNodes;
                }

                RuntimeContractMethods runtimeContracts =
                    new RuntimeContractMethods(userSpecifiedContractType,
                        cnForRuntime, assemblyNode, options.throwOnFailure, options.level, options.publicSurfaceOnly,
                        options.callSiteRequires,
                        options.recursionGuard, options.hideFromDebugger, options.IsLegacyModeAssembly);

                Rewriter rewriter = new Rewriter(assemblyNode, runtimeContracts, options.EmitError,
                    options.inheritInvariants, options.skipQuantifiers);

                rewriter.Verbose = 0 < options.verbose;
                rewriter.Visit(assemblyNode);

                // Perform this check only when there are no out-of-band contracts in use due to rewriter bug #336
                if (contractAssembly == null)
                {
                    PostRewriteChecker checker = new PostRewriteChecker(options.EmitError);
                    checker.Visit(assemblyNode);
                }
            }

            //Console.WriteLine(">>>Finished Rewriting<<<");

            // Set metadata version for target the same as for the source

            TargetPlatform.TargetRuntimeVersion = assemblyNode.TargetRuntimeVersion;

            // Write out the assembly (optional)

            if (options.rewrite || options.passthrough)
            {
                bool updateInPlace = options.output == "same";

                string pdbFile = Path.ChangeExtension(options.assembly, ".pdb");
                bool pdbExists = File.Exists(pdbFile);

                string backupAssembly = options.assembly + ".original";
                string backupPDB = pdbFile + ".original";


                if (updateInPlace)
                {
                    // Write the rewritten assembly in a temporary location.
                    options.output = options.assembly;

                    MoveAssemblyFileAndPDB(options.output, pdbFile, pdbExists, backupAssembly, backupPDB);
                }

                // Write the assembly.
                // Don't pass the debugInfo flag to WriteModule unless the PDB file exists.
                assemblyNode.WriteModule(options.output, options.debug && pdbExists && options.writePDBFile);

                string outputDir = updateInPlace
                    ? Path.GetDirectoryName(options.assembly)
                    : Path.GetDirectoryName(options.output);

                // Re-attach external file resources to the new output assembly.
                MoveModuleResources(assemblyNode, outputDir);

#if false
        if (oldPeVerifyCode == 0)
        {
          var newPeVerifyCode = PEVerify(assemblyNode.Location, originalsourceDir);
          if (newPeVerifyCode > 0)
          {
            if (updateInPlace)
            {
              // move original back in place
              MoveAssemblyFileAndPDB(backupAssembly, backupPDB, pdbExists, options.output, pdbFile);
            }
            throw new Exception("Rewrite failed to produce verifiable assembly");
          }
          else if (newPeVerifyCode == 0)
          {
            Console.WriteLine("rewriter output verified");
          }
        }
#endif
                if (updateInPlace)
                {
                    if (!options.keepOriginalFiles)
                    {
                        try
                        {
                            File.Delete(backupAssembly);
                        }
                        catch
                        {
                            // there are situations where the exe is still in use
                        }
                        if (options.debug && pdbExists && options.writePDBFile)
                        {
                            try
                            {
                                File.Delete(backupPDB);
                            }
                            catch
                            {
                                // I know this is stupid, but somehow on some machines we get an AccessError trying to delete the pdb.
                                // so we leave it in place.
                            }
                        }
                    }
                }
            }
        }
        private async Task<Document> MoveDeclarationNearReferenceAsync(Document document, State state, CancellationToken cancellationToken)
        {
            var innermostStatements =
                state.InnermostBlock.Statements.Where(s => s != state.DeclarationStatement).ToList();
            var innermostAffectedIndex = innermostStatements.IndexOf(state.FirstStatementAffectedInInnermostBlock);

            var crossesMeaningfulBlock = CrossesMeaningfulBlock(state);
            var warningAnnotation = crossesMeaningfulBlock
                ? WarningAnnotation.Create(CSharpFeaturesResources.Warning_colon_Declaration_changes_scope_and_may_change_meaning)
                : null;

            var canMergeDeclarationAndAssignment = await CanMergeDeclarationAndAssignmentAsync(document, state, cancellationToken).ConfigureAwait(false);
            if (canMergeDeclarationAndAssignment)
            {
                // Replace the first reference with a new declaration.
                var declarationStatement = CreateMergedDeclarationStatement(state, state.FirstStatementAffectedInInnermostBlock);
                declarationStatement = warningAnnotation == null
                    ? declarationStatement
                    : declarationStatement.WithAdditionalAnnotations(warningAnnotation);

                innermostStatements[innermostAffectedIndex] = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation);
            }
            else
            {
                // If we're not merging with an existing declaration, make the declaration semantically
                // explicit to improve the chances that it won't break code.
                var explicitDeclarationStatement = await Simplifier.ExpandAsync(state.DeclarationStatement, document, cancellationToken: cancellationToken).ConfigureAwait(false);

                // place the declaration above the first statement that references it.
                var declarationStatement = warningAnnotation == null
                    ? explicitDeclarationStatement
                    : explicitDeclarationStatement.WithAdditionalAnnotations(warningAnnotation);

                innermostStatements.Insert(innermostAffectedIndex, declarationStatement.WithAdditionalAnnotations(Formatter.Annotation));
            }

            var newInnermostBlock = state.InnermostBlock.WithStatements(
                    SyntaxFactory.List<StatementSyntax>(innermostStatements)).WithAdditionalAnnotations(Formatter.Annotation);

            var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
            var rewriter = new Rewriter(state.InnermostBlock, newInnermostBlock, state.OutermostBlock, state.DeclarationStatement);
            var newRoot = rewriter.Visit(tree.GetRoot(cancellationToken));

            return document.WithSyntaxRoot(newRoot);
        }
        private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var curlyBracketToken = syntaxRoot.FindToken(diagnostic.Location.SourceSpan.Start);
            var curlyBracketLine = curlyBracketToken.GetLineSpan().StartLinePosition.Line;
            var curlyBracketReplacementToken = curlyBracketToken;

            var indentationOptions = IndentationOptions.FromDocument(document);
            var indentationSteps = DetermineIndentationSteps(indentationOptions, curlyBracketToken);

            var previousToken = curlyBracketToken.GetPreviousToken();
            var nextToken = curlyBracketToken.GetNextToken();

            var rewriter = new Rewriter();

            if (IsAccessorWithSingleLineBlock(previousToken, curlyBracketToken))
            {
                var newTrailingTrivia = previousToken.TrailingTrivia
                    .WithoutTrailingWhitespace()
                    .Add(SyntaxFactory.Space);

                rewriter.AddReplacement(previousToken, previousToken.WithTrailingTrivia(newTrailingTrivia));

                curlyBracketReplacementToken = curlyBracketReplacementToken.WithLeadingTrivia(curlyBracketToken.LeadingTrivia.WithoutLeadingWhitespace());
            }
            else
            {
                // Check if we need to apply a fix before the curly bracket
                if (previousToken.GetLineSpan().StartLinePosition.Line == curlyBracketLine)
                {
                    var sharedTrivia = curlyBracketReplacementToken.LeadingTrivia.WithoutTrailingWhitespace();
                    var previousTokenNewTrailingTrivia = previousToken.TrailingTrivia
                        .WithoutTrailingWhitespace()
                        .AddRange(sharedTrivia)
                        .Add(SyntaxFactory.CarriageReturnLineFeed);

                    rewriter.AddReplacement(previousToken, previousToken.WithTrailingTrivia(previousTokenNewTrailingTrivia));

                    curlyBracketReplacementToken = curlyBracketReplacementToken.WithLeadingTrivia(IndentationHelper.GenerateWhitespaceTrivia(indentationOptions, indentationSteps));
                }

                // Check if we need to apply a fix after the curly bracket
                // if a closing curly bracket is followed by a semi-colon or closing paren, no fix is needed.
                if ((nextToken.GetLineSpan().StartLinePosition.Line == curlyBracketLine) &&
                    (!curlyBracketToken.IsKind(SyntaxKind.CloseBraceToken) || !IsValidFollowingToken(nextToken)))
                {
                    var sharedTrivia = nextToken.LeadingTrivia.WithoutTrailingWhitespace();
                    var newTrailingTrivia = curlyBracketReplacementToken.TrailingTrivia
                        .WithoutTrailingWhitespace()
                        .AddRange(sharedTrivia)
                        .Add(SyntaxFactory.CarriageReturnLineFeed);

                    int newIndentationSteps;
                    if (curlyBracketToken.IsKind(SyntaxKind.OpenBraceToken))
                    {
                        newIndentationSteps = indentationSteps + 1;
                    }
                    else if (nextToken.IsKind(SyntaxKind.CloseBraceToken))
                    {
                        newIndentationSteps = Math.Max(0, indentationSteps - 1);
                    }
                    else
                    {
                        newIndentationSteps = indentationSteps;
                    }

                    rewriter.AddReplacement(nextToken, nextToken.WithLeadingTrivia(IndentationHelper.GenerateWhitespaceTrivia(indentationOptions, newIndentationSteps)));

                    curlyBracketReplacementToken = curlyBracketReplacementToken.WithTrailingTrivia(newTrailingTrivia);
                }
            }

            rewriter.AddReplacement(curlyBracketToken, curlyBracketReplacementToken);

            var newSyntaxRoot = rewriter.Visit(syntaxRoot).WithoutFormatting();
            return document.WithSyntaxRoot(newSyntaxRoot);
        }
Beispiel #38
0
      private static void KaelsArchitecture(AssemblyNode assemblyNode) {

    // Finish decompiling expressions where CCI left off.
        new Abnormalizer().Visit(assemblyNode);
        

    // Check and extract all inline foxtrot contracts and place them in the object model.
        Checker checker = new Checker(new ContractNodes(assemblyNode));
        bool errorFound = false;
        checker.ErrorFound += delegate(System.CodeDom.Compiler.CompilerError error) {
          if (!error.IsWarning || warningLevel > 0) {
            Console.WriteLine(error.ToString());
          }
          errorFound |= !error.IsWarning;
        };
        checker.Visit(assemblyNode);
        if (errorFound)
          return;
        

        if (verify) {
          throw new NotImplementedException("Static verification is not yet implemented.");
        }

    // Write out the assembly, possibly injecting the runtime checks
        if (rewrite || passthrough) {
          // Reload the assembly to flush out the abnormalized contracts since the rewriter can't handle them yet.
          assemblyNode = LoadAssembly();

          if (!passthrough) {
            // Rewrite the assembly in memory.
            Rewriter rewriter = new Rewriter(new ContractNodes(assemblyNode));
            rewriter.InlinePreconditions = false;
            rewriter.InlinePostconditions = false;
            rewriter.InlineInvariant = false;
            rewriter.Verbose = verbose;
            rewriter.Decompile = decompile;
            rewriter.Visit(assemblyNode);
          }

          if (output == "same") {
            // Save the rewritten assembly to a temporary location.
            output = Path.Combine(Path.GetTempPath(), Path.GetFileName(assembly));

            // Re-attach external file resources to the new output assembly.
            MoveModuleResources(assemblyNode, output);

            // Save the rewritten assembly.
            assemblyNode.WriteModule(output, debug);

            // Make a copy of the original assembly and PDB.
            File.Delete(assembly + ".original");
            File.Delete(Path.ChangeExtension(assembly, ".pdb") + ".original");
            File.Move(assembly, assembly + ".original");
            File.Move(Path.ChangeExtension(assembly, ".pdb"), Path.ChangeExtension(assembly, ".pdb") + ".original");

            // Move the rewritten assembly and PDB to the original location.
            File.Move(output, assembly);
            File.Move(Path.ChangeExtension(output, ".pdb"), Path.ChangeExtension(assembly, ".pdb"));
          } else {
            // Re-attach external file resources to the new output assembly.
            MoveModuleResources(assemblyNode, output);

            // Save the rewritten assembly.
            assemblyNode.WriteModule(output, debug);
          }
        }
      }
		/// <summary>
		///     Normalizes the <paramref name="methodDeclaration" />.
		/// </summary>
		protected override SyntaxNode Normalize(MethodDeclarationSyntax methodDeclaration)
		{
			var returnCount = methodDeclaration.Descendants<ReturnStatementSyntax>().Count();

			// If there is no return statement within the method's body, there's nothing to do
			if (returnCount == 0)
				return methodDeclaration;

			// If there is only one return and it is the last method body's last statement, there's nothing to do
			if (returnCount == 1 && methodDeclaration.Body.Statements[methodDeclaration.Body.Statements.Count - 1] is ReturnStatementSyntax)
				return methodDeclaration;

			// Otherwise, we have to normalize the method
			var nameScope = methodDeclaration.GetNameScope(SemanticModel, includeLocals: true);
			var symbol = methodDeclaration.GetMethodSymbol(SemanticModel);

			_returnsValue = !symbol.ReturnsVoid;
			_hasReturnedVariable = SyntaxFactory.IdentifierName(nameScope.MakeUnique("hasReturned"));
			_returnValueVariable = _returnsValue ? SyntaxFactory.IdentifierName(nameScope.MakeUnique("returnValue")) : null;

			var rewriter = new Rewriter(Syntax, _hasReturnedVariable);
			methodDeclaration = (MethodDeclarationSyntax)rewriter.Visit(methodDeclaration);
			methodDeclaration = (MethodDeclarationSyntax)base.Normalize(methodDeclaration);

			// Generate the declarations for the local variables
			var hasReturnedLocal = Syntax.LocalDeclarationStatement(Syntax.TypeExpression<bool>(SemanticModel),
				_hasReturnedVariable.Identifier.ValueText, Syntax.FalseLiteralExpression());
			var statements = methodDeclaration.Body.Statements.Insert(0, (StatementSyntax)hasReturnedLocal);

			if (_returnsValue)
			{
				var returnValueLocal = Syntax.LocalDeclarationStatement(symbol.ReturnType, _returnValueVariable.Identifier.ValueText);
				statements = statements.Insert(0, (StatementSyntax)returnValueLocal);

				// If the method returns a value, add the final return statement, which by now is the only one within the entire method body
				statements = statements.Add((StatementSyntax)Syntax.ReturnStatement(_returnValueVariable));
			}

			return methodDeclaration.WithBody(SyntaxFactory.Block(statements)).NormalizeWhitespace();
		}