Пример #1
0
        public BuildResult Apply(IDictionary <string, string> substitutions, bool debug)
        {
            var analyzer = new Analyzer(script.Compilation, substitutions);
            var analyzed = analyzer.Analyze();

            var rewriter  = new Rewriter(script.Compilation, analyzed);
            var rewritten = rewriter.Rewrite();

            byte[] assembly;
            byte[] symbols = null;

            if (debug)
            {
                EmitDebug(rewritten, out assembly, out symbols);
            }
            else
            {
                Emit(rewritten, out assembly);
            }

            return(new BuildResult(
                       analyzed.Tasks.ToArray(),
                       script.References.ToArray(),
                       rewriter.Captured.ToArray(),
                       assembly, symbols
                       ));
        }
Пример #2
0
        protected override async Task FixAllAsync(
            Document document, ImmutableArray <Diagnostic> diagnostics,
            SyntaxEditor editor, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
        {
            using var spansDisposer = ArrayBuilder <TextSpan> .GetInstance(diagnostics.Length, out var spans);

            foreach (var diagnostic in diagnostics)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var switchLocation = diagnostic.AdditionalLocations[0];
                if (spans.Any((s, nodeSpan) => s.Contains(nodeSpan), switchLocation.SourceSpan))
                {
                    // Skip nested switch expressions in case of a fix-all operation.
                    continue;
                }

                spans.Add(switchLocation.SourceSpan);

                var properties                = diagnostic.Properties;
                var nodeToGenerate            = (SyntaxKind)int.Parse(properties[Constants.NodeToGenerateKey] !);
                var shouldRemoveNextStatement = bool.Parse(properties[Constants.ShouldRemoveNextStatementKey] !);

                var declaratorToRemoveLocation = diagnostic.AdditionalLocations.ElementAtOrDefault(1);
                var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                SyntaxNode? declaratorToRemoveNode = null;
                ITypeSymbol?declaratorToRemoveType = null;

                if (declaratorToRemoveLocation != null)
                {
                    declaratorToRemoveNode = declaratorToRemoveLocation.FindNode(cancellationToken);
                    declaratorToRemoveType = semanticModel.GetDeclaredSymbol(declaratorToRemoveNode, cancellationToken).GetSymbolType();
                }

                var switchStatement = (SwitchStatementSyntax)switchLocation.FindNode(getInnermostNodeForTie: true, cancellationToken);

                var switchExpression = Rewriter.Rewrite(
                    switchStatement, semanticModel, declaratorToRemoveType, nodeToGenerate,
                    shouldMoveNextStatementToSwitchExpression: shouldRemoveNextStatement,
                    generateDeclaration: declaratorToRemoveLocation is not null,
                    cancellationToken);

                editor.ReplaceNode(switchStatement, switchExpression.WithAdditionalAnnotations(Formatter.Annotation));

                if (declaratorToRemoveLocation is not null)
                {
                    editor.RemoveNode(declaratorToRemoveLocation.FindNode(cancellationToken));
                }

                if (shouldRemoveNextStatement)
                {
                    // Already morphed into the top-level switch expression.
                    var nextStatement = switchStatement.GetNextStatement();
                    Contract.ThrowIfNull(nextStatement);
                    Debug.Assert(nextStatement.IsKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement));
                    editor.RemoveNode(nextStatement.IsParentKind(SyntaxKind.GlobalStatement) ? nextStatement.GetRequiredParent() : nextStatement);
                }
            }
        }
Пример #3
0
        public void Test_Rewriter()
        {
            ulong writeCount = 0;
            ulong readCount  = 0;

            var w = new Rewriter(100);

            for (var i = 0; i < 1000000; i++)
            {
                var a = RandBytes(100);
                var b = new byte[a.Length];
                w.Push(a, 0, a.Length);
                writeCount += (ulong)a.Length;

                var remind = a.Length;
                var offset = 0;
                while (remind > 0)
                {
                    var size = rand.Next(remind) + 1;

                    using (MemoryStream ms = new MemoryStream(b, offset, b.Length - offset)) {
                        Assert.True(w.Rewrite(ms, writeCount, readCount));
                    }

                    readCount += (ulong)size;
                    offset    += size;
                    remind    -= size;
                }

                Assert.True(BytesEquals(a, b));
            }
        }
Пример #4
0
        /// <summary>
        /// Applies an accelerator-specialization transformation.
        /// </summary>
        protected override bool PerformTransformation(
            IRContext context,
            Method.Builder builder)
        {
            var toImplement = new List <Value>(16);
            var data        = new SpecializerData(this, context, toImplement);

            if (!Rewriter.Rewrite(builder.SourceBlocks, builder, data))
            {
                return(false);
            }

            foreach (var value in toImplement)
            {
                switch (value)
                {
                case DebugAssertOperation assert:
                    Implement(context, builder, builder[assert.BasicBlock], assert);
                    break;

                case WriteToOutput write:
                    Implement(context, builder, builder[write.BasicBlock], write);
                    break;

                case AsAligned aligned:
                    Implement(context, builder, builder[aligned.BasicBlock], aligned);
                    break;

                default:
                    throw builder.GetInvalidOperationException();
                }
            }
            return(true);
        }
        public void Load()
        {
            Assembly assembly       = Assembly.GetExecutingAssembly();
            var      appDomainSetup = new AppDomainSetup
            {
                ApplicationBase = Path.GetDirectoryName(assembly.Location)
            };

            this.testDomain = AppDomain.CreateDomain("TestDomain", null, appDomainSetup);
            this.testDomain.AssemblyResolve += (s, e) =>
            {
                return(Assembly.LoadFrom(e.Name));
            };
            this.loader = (Loader)this.testDomain.CreateInstanceAndUnwrap(assembly.Location, typeof(Loader).FullName);

            using (var rewritten = new MemoryStream())
            {
                RewriterOptions options = new RewriterOptions
                {
                    ForceAssemblyRename = "RewrittenForTest",
                    Assembly            = assembly.Location,
                    OutputFile          = rewritten,
                    ThrowOnFailure      = true,
                    WritePdbFile        = false,
                };
                Rewriter.Rewrite(options);
                byte [] bytes = rewritten.ToArray();
                this.loader.Load(bytes);
            }
        }
Пример #6
0
 /// <summary>
 /// Applies an accelerator-specialization transformation.
 /// </summary>
 protected override bool PerformTransformation(
     IRContext context,
     Method.Builder builder) =>
 Rewriter.Rewrite(
     builder.SourceBlocks,
     builder,
     new SpecializerData(this, context));
Пример #7
0
        private IMarkdownToken RewriteToken(IMarkdownToken token)
        {
            var rewritedToken = token;
            var newToken      = Rewriter.Rewrite(this, rewritedToken);

            if (newToken != null)
            {
                rewritedToken = newToken;
            }
            return(rewritedToken);
        }
Пример #8
0
        /// <summary>
        /// Applies the UCE transformation.
        /// </summary>
        protected override bool PerformTransformation(Method.Builder builder)
        {
            var scope = builder.CreateScope();

            // Fold branch targets (if possible)
            bool updated = false;

            foreach (var block in scope)
            {
                // Get the conditional terminator
                var terminator = block.GetTerminatorAs <ConditionalBranch>();
                if (terminator == null || !terminator.CanFold)
                {
                    continue;
                }

                // Fold branch
                var blockBuilder = builder[block];
                terminator.Fold(blockBuilder);

                updated = true;
            }

            // Check for changes
            if (!updated)
            {
                return(false);
            }

            // Find all unreachable blocks
            var updatedScope = builder.CreateScope();

            foreach (var block in scope)
            {
                if (!updatedScope.Contains(block))
                {
                    // Block is unreachable -> remove all operations
                    var blockBuilder = builder[block];
                    blockBuilder.Clear();
                }
            }

            // Update all phi values
            Rewriter.Rewrite(
                updatedScope,
                builder,
                new PhiArgumentRemapper(updatedScope));

            return(true);
        }
Пример #9
0
        protected override Task FixAllAsync(Document document, ImmutableArray <Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken)
        {
            using var spansDisposer = ArrayBuilder <TextSpan> .GetInstance(diagnostics.Length, out var spans);

            foreach (var diagnostic in diagnostics)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var switchLocation = diagnostic.AdditionalLocations[0];
                if (spans.Any((s, nodeSpan) => s.Contains(nodeSpan), switchLocation.SourceSpan))
                {
                    // Skip nested switch expressions in case of a fix-all operation.
                    continue;
                }

                spans.Add(switchLocation.SourceSpan);

                var properties                = diagnostic.Properties;
                var nodeToGenerate            = (SyntaxKind)int.Parse(properties[Constants.NodeToGenerateKey]);
                var shouldRemoveNextStatement = bool.Parse(properties[Constants.ShouldRemoveNextStatementKey]);

                var declaratorToRemoveLocationOpt = diagnostic.AdditionalLocations.ElementAtOrDefault(1);

                var switchStatement  = (SwitchStatementSyntax)switchLocation.FindNode(cancellationToken);
                var switchExpression = Rewriter.Rewrite(switchStatement, nodeToGenerate,
                                                        shouldMoveNextStatementToSwitchExpression: shouldRemoveNextStatement,
                                                        generateDeclaration: declaratorToRemoveLocationOpt is object);

                editor.ReplaceNode(switchStatement, switchExpression.WithAdditionalAnnotations(Formatter.Annotation));

                if (declaratorToRemoveLocationOpt is object)
                {
                    editor.RemoveNode(declaratorToRemoveLocationOpt.FindNode(cancellationToken));
                }

                if (shouldRemoveNextStatement)
                {
                    // Already morphed into the top-level switch expression.
                    var nextStatement = switchStatement.GetNextStatement();
                    Debug.Assert(nextStatement.IsKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement));
                    editor.RemoveNode(nextStatement);
                }
            }

            return(Task.CompletedTask);
        }
        protected override async Task FixAllAsync(Document document, ImmutableArray <Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken)
        {
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            var spans = ArrayBuilder <TextSpan> .GetInstance(diagnostics.Length);

            try
            {
                foreach (var diagnostic in diagnostics)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var span = diagnostic.AdditionalLocations[0].SourceSpan;
                    if (spans.Any((s, nodeSpan) => s.Contains(nodeSpan), span))
                    {
                        // Skip nested switch expressions in case of a fix-all operation.
                        continue;
                    }

                    spans.Add(span);

                    var properties                = diagnostic.Properties;
                    var nodeToGenerate            = (SyntaxKind)int.Parse(properties[Constants.NodeToGenerateKey]);
                    var shouldRemoveNextStatement = bool.Parse(properties[Constants.ShouldRemoveNextStatementKey]);

                    var switchStatement = (SwitchStatementSyntax)editor.OriginalRoot.FindNode(span);
                    editor.ReplaceNode(switchStatement,
                                       Rewriter.Rewrite(switchStatement, semanticModel, editor,
                                                        nodeToGenerate, shouldMoveNextStatementToSwitchExpression: shouldRemoveNextStatement)
                                       .WithAdditionalAnnotations(Formatter.Annotation));

                    if (shouldRemoveNextStatement)
                    {
                        // Already morphed into the top-level switch expression.
                        var nextStatement = switchStatement.GetNextStatement();
                        Debug.Assert(nextStatement.IsKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement));
                        editor.RemoveNode(nextStatement);
                    }
                }
            }
            finally
            {
                spans.Free();
            }
        }
Пример #11
0
        private void txtOriginal_TextChanged(object sender, EventArgs e)
        {
            lblSummarized.Text = Rewriter.Rewrite(txtOriginal.Text, strLanguage);

            switch (cboSyntax.SelectedItem.ToString().Replace(".synx", ""))
            {
            case "Español":
                lblCharCountOriginal.Text   = "Caracteres: " + txtOriginal.Text.Count();
                lblCharCountSummarized.Text = "Caracteres: " + lblSummarized.Text.Count();
                break;

            default:
            case "English":
                lblCharCountOriginal.Text   = "Char count: " + txtOriginal.Text.Count();
                lblCharCountSummarized.Text = "Char count: " + lblSummarized.Text.Count();
                break;
            }
        }
            private Expression RewriteHandler(Expression body)
            {
                //
                // 1. Get accessors to the resulting Value and Index.
                //
                var leaveResultValue = Expression.PropertyOrField(_leaveResult, "Value");

                //
                // 2. Compute gotos that leave the body.
                //
                var gotoScanner = new GotoScanner(_labelScanner.Labels);

                gotoScanner.Visit(body);

                //
                // 3. Rewrite body.
                //
                var leaveLabel = Expression.Label(typeof(LeaveHandlerData));
                var rewriter   = new Rewriter(leaveLabel, gotoScanner.LeaveLabels);
                var newBody    = rewriter.Rewrite(body);

                //
                // 4. Create dispatch table.
                //
                if (gotoScanner.LeaveLabels.Count > 0)
                {
                    _jumpTable.AddRange(gotoScanner.LeaveLabels.Select(kv =>
                    {
                        var index = Expression.Constant(kv.Value);
                        var label = kv.Key;
                        var value = label.Type == typeof(void) ? null : Expression.Convert(leaveResultValue, label.Type);
                        var jump  = Expression.Goto(label, value);
                        return(Expression.SwitchCase(jump, index));
                    }));
                }

                return(newBody);
            }
Пример #13
0
        static void Main(string [] args)
        {
            RewriterOptions options = new RewriterOptions();

            bool   showOptions = false;
            string showMsg     = null;

            var optionSet = new OptionSet
            {
                { "help", "Show this help.", v => showOptions = v != null },
                { "debug", "Use MDB or PDB debug information (default=true).", v => options.Debug = v != null },
                { "level=", "Instrumentation level, 0 - 4 (default=4).", (int var) => options.Level = var },
                { "writePDBFile", "Write MDB or PDB file (default=true).", v => options.WritePdbFile = v != null },
                { "rewrite", "Rewrite the assembly (default=true).", v => options.Rewrite = v != null },
                { "assembly=", "Assembly to rewrite.", v => options.Assembly = v },
                { "breakIntoDebugger|break", "Break into debugger on contract failure.", v => options.BreakIntoDebugger = v != null },
                { "throwOnFailure|throw", "Throw ContractException on contract failure.", v => options.ThrowOnFailure = v != null },
                { "output|out=", "Output filename of rewritten file.", v => options.OutputFile = v },
            };

            try
            {
                optionSet.Parse(args);
            }
            catch (OptionException e)
            {
                showOptions = true;
                showMsg     = e.Message;
            }

            if (showOptions)
            {
                Console.WriteLine("ccrewrite");
                Console.WriteLine();
                Console.WriteLine("Options:");
                optionSet.WriteOptionDescriptions(Console.Out);
                Console.WriteLine();
                if (showMsg != null)
                {
                    Console.WriteLine(showMsg);
                    Console.WriteLine();
                }
                return;
            }

            var results = Rewriter.Rewrite(options);

            if (results.AnyErrors)
            {
                foreach (var error in results.Errors)
                {
                    Console.WriteLine("Error: " + error);
                }
            }
            if (results.AnyWarnings)
            {
                foreach (var warning in results.Warnings)
                {
                    Console.WriteLine("Warning: " + warning);
                }
            }

            Console.WriteLine();
            Console.WriteLine("*** done ***");
            //Console.ReadKey ();
        }
Пример #14
0
 private void btnAdd_Click(object sender, EventArgs e)
 {
     ListedTextFileManager.Write(txtTopic.Text, txtCurrentConcept.Text.ToUpper() + ". " + Rewriter.Rewrite(txtOriginal.Text, strLanguage), strLanguage);
 }
Пример #15
0
        static string GetRewrittenString(string input)
        {
            var rewriter = new Rewriter(input);

            return(rewriter.Rewrite());
        }
Пример #16
0
 /// <summary>
 /// Applies an accelerator-specialization transformation.
 /// </summary>
 protected override bool PerformTransformation(Method.Builder builder) =>
 Rewriter.Rewrite(builder, this);
Пример #17
0
 private void cboSyntax_SelectedValueChanged(object sender, EventArgs e)
 {
     strLanguage        = cboSyntax.SelectedItem.ToString().Replace(".synx", "");
     lblSummarized.Text = Rewriter.Rewrite(txtOriginal.Text, strLanguage);
     Translate();
 }
Пример #18
0
 /// <summary>
 /// Applies the address-space inference transformation.
 /// </summary>
 protected override bool PerformTransformation(Method.Builder builder) =>
 Rewriter.Rewrite(builder.SourceBlocks, builder);
            private Expression RewriteHandler(Expression body)
            {
                //
                // 1. Get accessors to the resulting Value and Index.
                //
                var leaveResultValue = Expression.PropertyOrField(_leaveResult, "Value");

                //
                // 2. Compute gotos that leave the body.
                //
                var gotoScanner = new GotoScanner(_labelScanner.Labels);
                gotoScanner.Visit(body);

                //
                // 3. Rewrite body.
                //
                var leaveLabel = Expression.Label(typeof(LeaveHandlerData));
                var rewriter = new Rewriter(leaveLabel, gotoScanner.LeaveLabels);
                var newBody = rewriter.Rewrite(body);

                //
                // 4. Create dispatch table.
                //
                if (gotoScanner.LeaveLabels.Count > 0)
                {
                    _jumpTable.AddRange(gotoScanner.LeaveLabels.Select(kv =>
                    {
                        var index = Expression.Constant(kv.Value);
                        var label = kv.Key;
                        var value = label.Type == typeof(void) ? null : Expression.Convert(leaveResultValue, label.Type);
                        var jump = Expression.Goto(label, value);
                        return Expression.SwitchCase(jump, index);
                    }));
                }

                return newBody;
            }