Пример #1
0
        private void calculateButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ClearScreen();

                string formula = formulaTextBox.Text;

                TokenReader reader = new TokenReader(CultureInfo.InvariantCulture);
                List<Token> tokens = reader.Read(formula);

                ShowTokens(tokens);

                AstBuilder astBuilder = new AstBuilder();
                Operation operation = astBuilder.Build(tokens);

                ShowAbstractSyntaxTree(operation);

                Dictionary<string, double> variables = new Dictionary<string, double>();
                foreach (Variable variable in GetVariables(operation))
                {
                    double value = AskValueOfVariable(variable);
                    variables.Add(variable.Name, value);
                }

                IExecutor executor = new Interpreter();
                double result = executor.Execute(operation, variables);

                resultTextBox.Text = "" + result;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Пример #2
0
        public void AstBuilder_ComplexExpression_Build()
        {
            var tree = new Ast("+", true);
            tree.Operands.Add(new Ast("4"));
            tree.Operands.Add(new Ast("6"));

            var buffer = new Ast("/", true);
            buffer.Operands.Add(new Ast("81"));
            buffer.Operands.Add(new Ast("-3"));

            var anotherBuffer = new Ast("*", true);
            anotherBuffer.Operands.Add(new Ast("3"));
            anotherBuffer.Operands.Add(new Ast("3"));
            buffer.Operands.Add(anotherBuffer);

            tree.Operands.Add(buffer);

            buffer = new Ast("-", true);
            buffer.Operands.Add(new Ast("10"));
            buffer.Operands.Add(new Ast("12"));

            tree.Operands.Add(buffer);
            var input = "(+ 4 6 (/ 81 -3 (* 3 3 ))( - 10 12 ))";

            var actualTree = new AstBuilder().Build(new Tokenizer().GetTokens(input));
            Assert.IsTrue(actualTree.Equals(tree));
        }
		public void should_recognize_as(string input, AstBuilder<LanguageConstruct> expected)
		{
			var subject = new RecognizeLines();
			var result = subject.ParseWholeFile(input);

			result.Should()
				.BeRecognizedAs(expected);
		}
        static void RunOnCore()
        {
            Console.Write("Dry run...");
            DateTime startDryRun = DateTime.UtcNow;
            {
                var _para = new ReaderParameters(ReadingMode.Immediate)
                {
                    AssemblyResolver = new AssemblyResolver(),
                    ReadSymbols = false
                };
                var sys = AssemblyDefinition.ReadAssembly(typeof(TestingLogic).Assembly.Location, _para);
                var _dc = new DecompilerContext(sys.MainModule);
                var _astb = new AstBuilder(_dc);
                _astb.AddAssembly(sys);
                _astb.RunTransformations();
                _astb.GenerateCode(new DummyOutput());
            }
            TimeSpan dryRunTime = DateTime.UtcNow - startDryRun;
            Console.WriteLine(" O.K. " + dryRunTime.TotalSeconds.ToString("0.000") + " s.");

            Console.Write("Press Esc to skip large assembly reading");
            if (Console.ReadKey().Key != ConsoleKey.Escape)
            {
                Console.Write("Reading assembly...");
                DateTime startReading = DateTime.UtcNow;
                var msco = AssemblyDefinition.ReadAssembly(typeof(int).Assembly.Location);
                TimeSpan readAssemblyTime = DateTime.UtcNow - startReading;
                Console.WriteLine(" O.K. " + readAssemblyTime.TotalSeconds.ToString("0.000") + " s.");

                Console.Write("new DecompilerContext(), new AstBuilder()...");
                DateTime startNewContext = DateTime.UtcNow;
                var dc = new DecompilerContext(msco.MainModule);
                var astb = new AstBuilder(dc);
                TimeSpan newContextTime = DateTime.UtcNow - startNewContext;
                Console.WriteLine(" O.K. " + newContextTime.TotalSeconds.ToString("0.000") + " s.");

                Console.Write("AstBuilder.AddAssembly()...");
                DateTime startAddAssembly = DateTime.UtcNow;
                astb.AddAssembly(msco);
                TimeSpan decompilerInitTime = DateTime.UtcNow - startAddAssembly;
                Console.WriteLine(" O.K. " + decompilerInitTime.TotalSeconds.ToString("0.000") + " s.");

                Console.Write("AstBuilder.RunTransformations()...");
                DateTime startTransform = DateTime.UtcNow;
                astb.RunTransformations();
                TimeSpan transformTime = DateTime.UtcNow - startTransform;
                Console.WriteLine(" O.K. " + transformTime.TotalSeconds.ToString("0.000") + " s.");

                Console.Write("AstBuilder.GenerateCode()...");
                DateTime startGeneration = DateTime.UtcNow;
                astb.GenerateCode(new DummyOutput());
                TimeSpan generationTime = DateTime.UtcNow - startGeneration;
                Console.WriteLine(" O.K. " + generationTime.TotalSeconds.ToString("0.000") + " s.");

                Console.Write("Press any key to exit"); Console.ReadKey();
            }
        }
Пример #5
0
 public void TestBuildInvalidFormula1()
 {
     AstBuilder builder = new AstBuilder();
     Operation operation = builder.Build(new List<Token>() {
         new Token() { Value = '(', TokenType = TokenType.LeftBracket, StartPosition = 0 },
         new Token() { Value = 42, TokenType = TokenType.Integer, StartPosition = 1 },
         new Token() { Value = '+', TokenType = TokenType.Operation, StartPosition = 3 },
         new Token() { Value = 8, TokenType = TokenType.Integer, StartPosition = 4 },
         new Token() { Value = ')', TokenType = TokenType.RightBracket, StartPosition = 5 },
         new Token() { Value = '*', TokenType = TokenType.Operation, StartPosition = 6 },
     });
 }
Пример #6
0
        public void TestBuildFormula3()
        {
            AstBuilder builder = new AstBuilder();
            Operation operation = builder.Build(new List<Token>() {
                new Token() { Value = 2, TokenType = TokenType.Integer },
                new Token() { Value = '*', TokenType = TokenType.Operation },
                new Token() { Value = 8, TokenType = TokenType.Integer },
                new Token() { Value = '-', TokenType = TokenType.Operation },
                new Token() { Value = 3, TokenType = TokenType.Integer }
            });

            Substraction substraction = (Substraction)operation;
            Multiplication multiplication = (Multiplication)substraction.Argument1;

            Assert.AreEqual(3, ((Constant<int>)substraction.Argument2).Value);
            Assert.AreEqual(2, ((Constant<int>)multiplication.Argument1).Value);
            Assert.AreEqual(8, ((Constant<int>)multiplication.Argument2).Value);
        }
Пример #7
0
        public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
        {
            WriteCommentLine(output, TypeToString(method.DeclaringType, includeNamespace: true));
            AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: method.DeclaringType, isSingleMember: true);

            if (method.IsConstructor && !method.IsStatic && !method.DeclaringType.IsValueType)
            {
                // also fields and other ctors so that the field initializers can be shown as such
                AddFieldsAndCtors(codeDomBuilder, method.DeclaringType, method.IsStatic);
                RunTransformsAndGenerateCode(codeDomBuilder, output, options, new SelectCtorTransform(method));
            }
            else
            {
                codeDomBuilder.AddMethod(method);
                RunTransformsAndGenerateCode(codeDomBuilder, output, options);
            }
            NotifyDecompilationFinished(codeDomBuilder);
        }
Пример #8
0
        // (if () ...)
        public static AST Expand(Syntax stx, Environment env)
        {
            var list = stx.AsLinkedList <Value>();
            var argc = GetArgsCount(list);

            AssertArgsMinimum("if", "arity mismatch", 2, argc, list, stx);

            var keyword = list[0].AsSyntax();
            var cond    = list[1].AsSyntax();
            var then    = list[2].AsSyntax();
            var elsc    = argc < 3 ? null : list[3].AsSyntax();

            var cond_ast = AstBuilder.ExpandInternal(cond, env);
            var then_ast = AstBuilder.ExpandInternal(then, env);
            var else_ast = AstBuilder.ExpandInternal(elsc, env);

            return(new AstConditionIf(stx, keyword, cond_ast, then_ast, else_ast));
        }
Пример #9
0
		string TypeToString(ConvertTypeOptions options, TypeReference type, ICustomAttributeProvider typeAttributes = null)
		{
			var envProvider = new ILSpyEnvironmentProvider();
			var converter = new CSharpToVBConverterVisitor(envProvider);
			var astType = AstBuilder.ConvertType(type, typeAttributes, options);
			StringWriter w = new StringWriter();

			if (type.IsByReference) {
				w.Write("ByRef ");
				if (astType is NRefactory.CSharp.ComposedType && ((NRefactory.CSharp.ComposedType)astType).PointerRank > 0)
					((NRefactory.CSharp.ComposedType)astType).PointerRank--;
			}
			
			var vbAstType = astType.AcceptVisitor(converter, null);
			
			vbAstType.AcceptVisitor(new OutputVisitor(w, new VBFormattingOptions()), null);
			return w.ToString();
		}
Пример #10
0
        public void TestOptimizerIdempotentFunction()
        {
            Optimizer optimizer = new Optimizer(new Interpreter());

            TokenReader   tokenReader = new TokenReader(CultureInfo.InvariantCulture);
            IList <Token> tokens      = tokenReader.Read("test(var1, (2+3) * 500)");

            IFunctionRegistry functionRegistry = new FunctionRegistry(true);

            functionRegistry.RegisterFunction("test", (Func <double, double, double>)((a, b) => a + b));

            AstBuilder astBuilder = new AstBuilder(functionRegistry, true);
            Operation  operation  = astBuilder.Build(tokens);

            Function optimizedFuction = (Function)optimizer.Optimize(operation, functionRegistry, null);

            Assert.AreEqual(typeof(FloatingPointConstant), optimizedFuction.Arguments[1].GetType());
        }
Пример #11
0
        public void TestSortNode1()
        {
            // The connections of CBNs are
            //
            //  1 <----> 2
            //
            var model = Controller.DynamoModel;

            string openPath = Path.Combine(GetTestDirectory(), @"core\astbuilder\cyclic.dyn");

            model.Open(openPath);

            var builder = new AstBuilder(null);

            var sortedNodes = builder.TopologicalSort(model.CurrentWorkspace.Nodes);

            Assert.AreEqual(sortedNodes.Count(), 2);
        }
Пример #12
0
		IEnumerable<Tuple<string, string>> WriteAssemblyInfo(ModuleDefinition module, DecompilationOptions options, HashSet<string> directories)
		{
			// don't automatically load additional assemblies when an assembly node is selected in the tree view
			using (LoadedAssembly.DisableAssemblyLoad())
			{
				AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: module);
				codeDomBuilder.AddAssembly(module, onlyAssemblyLevel: true);
				codeDomBuilder.RunTransformations(transformAbortCondition);

				string prop = "Properties";
				if (directories.Add("Properties"))
					Directory.CreateDirectory(Path.Combine(options.SaveAsProjectDirectory, prop));
				string assemblyInfo = Path.Combine(prop, "AssemblyInfo" + this.FileExtension);
				using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, assemblyInfo)))
					codeDomBuilder.GenerateCode(new PlainTextOutput(w));
				return new Tuple<string, string>[] { Tuple.Create("Compile", assemblyInfo) };
			}
		}
Пример #13
0
        private static void WriteAssemblyInfo(ModuleDefinition module, DecompilationOptions options)
        {
            var path = Path.Combine(options.SaveAsProjectDirectory, Path.Combine("Properties", "AssemblyInfo" + lang.FileExtension));

            CreateParentDirectory(path);

            using (var w = new StreamWriter(path)) {
                var builder = new AstBuilder(
                    new DecompilerContext(module)
                {
                    CancellationToken = options.CancellationToken,
                    Settings          = options.DecompilerSettings
                });

                builder.AddAssembly(module, true);
                builder.GenerateCode(new PlainTextOutput(w));
            }
        }
Пример #14
0
        public EngineController(LibraryServices libraryServices, string geometryFactoryFileName, bool verboseLogging)
        {
            this.libraryServices           = libraryServices;
            libraryServices.LibraryLoaded += LibraryLoaded;
            CompilationServices            = new CompilationServices(libraryServices.LibraryManagementCore);

            liveRunnerServices = new LiveRunnerServices(this, geometryFactoryFileName);

            liveRunnerServices.ReloadAllLibraries(libraryServices.ImportedLibraries);
            libraryServices.SetLiveCore(LiveRunnerCore);

            codeCompletionServices = new CodeCompletionServices(LiveRunnerCore);

            astBuilder      = new AstBuilder(this);
            syncDataManager = new SyncDataManager();

            VerboseLogging = verboseLogging;
        }
Пример #15
0
        /// <summary>
        /// Compiles and decompiles a source code.
        /// </summary>
        /// <param name="code">The source code to copile.</param>
        /// <returns>The decompilation result of compiled source code.</returns>
        static string RoundtripCode(string code)
        {
            DecompilerSettings settings = new DecompilerSettings();

            settings.FullyQualifyAmbiguousTypeNames = false;
            AssemblyDefinition assembly   = Compile(code);
            AstBuilder         decompiler = new AstBuilder(new DecompilerContext(assembly.MainModule)
            {
                Settings = settings
            });

            decompiler.AddAssembly(assembly);
            new Helpers.RemoveCompilerAttribute().Run(decompiler.CompilationUnit);
            StringWriter output = new StringWriter();

            decompiler.GenerateCode(new PlainTextOutput(output));
            return(output.ToString());
        }
Пример #16
0
        public void TestBuildFormula1()
        {
            IFunctionRegistry registry = new MockFunctionRegistry();

            AstBuilder builder   = new AstBuilder(registry);
            Operation  operation = builder.Build(new List <Token>()
            {
                new Token()
                {
                    Value = '(', TokenType = TokenType.LeftBracket
                },
                new Token()
                {
                    Value = 42, TokenType = TokenType.Integer
                },
                new Token()
                {
                    Value = '+', TokenType = TokenType.Operation
                },
                new Token()
                {
                    Value = 8, TokenType = TokenType.Integer
                },
                new Token()
                {
                    Value = ')', TokenType = TokenType.RightBracket
                },
                new Token()
                {
                    Value = '*', TokenType = TokenType.Operation
                },
                new Token()
                {
                    Value = 2, TokenType = TokenType.Integer
                }
            });

            Multiplication multiplication = (Multiplication)operation;
            Addition       addition       = (Addition)multiplication.Argument1;

            Assert.AreEqual(42, ((Constant <int>)addition.Argument1).Value);
            Assert.AreEqual(8, ((Constant <int>)addition.Argument2).Value);
            Assert.AreEqual(2, ((Constant <int>)multiplication.Argument2).Value);
        }
Пример #17
0
        void GenerateCode(AstBuilder astBuilder, ITextOutput output)
        {
            var syntaxTree = astBuilder.SyntaxTree;

            syntaxTree.AcceptVisitor(new InsertParenthesesVisitor {
                InsertParenthesesForReadability = true
            });

            // Xml
            var dom = new XmlDocument();

            dom.AppendChild(dom.CreateElement("CodeDom")); // root node

            // generate AST
            VisitSyntaxTree(syntaxTree, dom);

            //Generate C# Code
            var csharpText      = new StringWriter();
            var csharpoutput    = new PlainTextOutput(csharpText);
            var outputFormatter = new TextOutputFormatter(csharpoutput)
            {
                FoldBraces = true
            };
            var formattingPolicy = FormattingOptionsFactory.CreateAllman();

            syntaxTree.AcceptVisitor(new CSharpOutputVisitor(outputFormatter, formattingPolicy));

            // insert to xml as cdata
            var csharpcode = dom.CreateElement("Code");
            var cdata      = dom.CreateCDataSection(csharpText.ToString());

            csharpcode.AppendChild(cdata);
            dom.DocumentElement.AppendChild(csharpcode);

            // write to output
            var text   = new StringWriter();
            var writer = new XmlTextWriter(text)
            {
                Formatting = Formatting.Indented
            };

            dom.WriteContentTo(writer);
            output.Write(text.ToString());
        }
Пример #18
0
        public void TestSortNode3()
        {
            // The connections of CBNs are
            //
            //   1 ----+
            //          \
            //   2 ----> 4
            //          /
            //   3 ----+
            //
            string openPath = Path.Combine(TestDirectory, @"core\astbuilder\multiinputs.dyn");

            OpenModel(openPath);

            var id1 = "1a00d6cb-f67d-4b79-a810-94145ad31486";
            var id2 = "8188eb2e-1746-4513-a51e-1dc8dfdb08e6";
            var id3 = "e5ef9374-389b-45d4-8ca3-44d52276a5cc";
            var id4 = "c342aed0-eea6-463d-b55f-ae260b0e5320";


            var nodes = CurrentDynamoModel.CurrentWorkspace.Nodes.ToList();

            var shuffle = new ShuffleUtil <NodeModel>(nodes);

            for (int i = 0; i < shuffleCount; ++i)
            {
                var sortedNodes = AstBuilder.TopologicalSort(shuffle.ShuffledList).ToList();
                Assert.AreEqual(sortedNodes.Count(), 4);

                List <string> ids = sortedNodes.Select(node => node.GUID.ToString()).ToList();

                var nodePosMap = new Dictionary <string, int>();
                for (int idx = 0; idx < ids.Count; ++idx)
                {
                    nodePosMap[ids[idx]] = idx;
                }

                // no matter the order of the input nodes, these invariants
                // should hold
                Assert.IsTrue(nodePosMap[id1] < nodePosMap[id4]);
                Assert.IsTrue(nodePosMap[id2] < nodePosMap[id4]);
                Assert.IsTrue(nodePosMap[id3] < nodePosMap[id4]);
            }
        }
Пример #19
0
        private IEnumerable <Tuple <string, string> > WriteCodeFilesInProject(ModuleDefinition module, DecompilationOptions options, HashSet <string> directories)
        {
            var files = module.Types.Where(t => IncludeTypeWhenDecompilingProject(t, options)).GroupBy(
                delegate(TypeDefinition type)
            {
                string file = cleanupName(type.Name) + this.FileExtension;

                if (string.IsNullOrEmpty(type.Namespace))
                {
                    return(file);
                }
                else
                {
                    string dir = cleanupName(type.Namespace);
                    if (directories.Add(dir))
                    {
                        CreateDirSafely(Path.Combine(options.SaveAsProjectDirectory, dir));
                    }
                    return(Path.Combine(dir, file));
                }
            }, StringComparer.OrdinalIgnoreCase).ToList();

            AstMethodBodyBuilder.ClearUnhandledOpcodes();
            //			Parallel.ForEach(
            //				files,
            //				new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
            //			delegate(IGrouping<string, TypeDefinition> file)
            foreach (IGrouping <string, TypeDefinition> file in files)
            {
                using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, file.Key)))
                {
                    AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: module);
                    foreach (TypeDefinition type in file)
                    {
                        codeDomBuilder.AddType(type);
                    }
                    codeDomBuilder.RunTransformations(transformAbortCondition);
                    codeDomBuilder.GenerateCode(new PlainTextOutput(w));
                }
            }
            //);
            AstMethodBodyBuilder.PrintNumberOfUnhandledOpcodes();
            return(files.Select(f => Tuple.Create("Compile", f.Key)).Concat(WriteAssemblyInfo(module, options, directories)));
        }
Пример #20
0
        private static IEnumerable<AssemblyClass> GenerateAssemblyMethodSource(string assemblyPath)
        {
            AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly (assemblyPath, new ReaderParameters (ReadingMode.Deferred) { ReadSymbols = true });
            AstBuilder astBuilder = null;
            foreach (var defmod in assemblyDefinition.Modules) {
                foreach (var typeInAssembly in defmod.Types) {
                    AssemblyClass klass = new AssemblyClass ();
                    klass.name = typeInAssembly.Name;
                    klass.namespase = typeInAssembly.Namespace;
                    astBuilder = new AstBuilder (new DecompilerContext (assemblyDefinition.MainModule) { CurrentType = typeInAssembly });
                    astBuilder.AddType (typeInAssembly);

                    StringWriter output = new StringWriter ();
                    astBuilder.GenerateCode (new PlainTextOutput (output));
                    klass.source = output.ToString ();
                    yield return klass;
                }
            }
        }
Пример #21
0
        public void TestSortNode6()
        {
            // The connections of CBNs are
            //
            //                   1
            //                   ^
            //                   |
            //                   2
            //                   ^
            //                   |
            //  6 <---- 4 <----> 3 <----> 5 ----> 7          8 <----> 9
            //
            var model = ViewModel.Model;

            string openPath = Path.Combine(GetTestDirectory(), @"core\astbuilder\complex.dyn");

            ViewModel.OpenCommand.Execute(openPath);

            var nodes        = model.CurrentWorkspace.Nodes.ToList();
            int shuffleCount = 10;
            var shuffle      = new ShuffleUtil <NodeModel>(nodes);

            for (int i = 0; i < shuffleCount; ++i)
            {
                nodes = shuffle.ShuffledList;

                var sortedNodes = AstBuilder.TopologicalSort(nodes).ToList();
                Assert.AreEqual(sortedNodes.Count(), 9);

                var nickNames  = sortedNodes.Select(node => Int32.Parse(node.NickName)).ToList();
                var nodePosMap = new Dictionary <int, int>();
                for (int idx = 0; idx < nickNames.Count; ++idx)
                {
                    nodePosMap[nickNames[idx]] = idx;
                }

                // no matter input nodes in whatever order, there invariants
                // should hold
                Assert.IsTrue(nodePosMap[1] > nodePosMap[2]);
                Assert.IsTrue(nodePosMap[6] > nodePosMap[4]);
                Assert.IsTrue(nodePosMap[7] > nodePosMap[5]);
            }
        }
Пример #22
0
        /// <summary>
        /// Build typescript ast.
        /// </summary>
        /// <param name="files">The typescript json files.</param>
        /// <returns>The ast document list</returns>
        private List <Document> BuildAst(List <string> files)
        {
            List <Document> tsDocs = new List <Document>();

            DateTime startTime = DateTime.Now;

            this.Log(string.Format("Starting build ast({0})", files.Count));

            foreach (string file in files)
            {
                AstBuilder builder = new AstBuilder();
                Document   doc     = builder.Build(file);

                tsDocs.Add(doc);
            }

            this.Log(string.Format("Finished after {0}s", (DateTime.Now - startTime).TotalSeconds.ToString("0.00")));
            return(tsDocs);
        }
Пример #23
0
        public void TestOptimizerNonIdempotentFunction()
        {
            Optimizer optimizer = new Optimizer(new Interpreter());

            TokenReader   tokenReader = new TokenReader(CultureInfo.InvariantCulture);
            IList <Token> tokens      = tokenReader.Read("test(500)");

            IFunctionRegistry functionRegistry = new FunctionRegistry(true);

            functionRegistry.RegisterFunction("test", (Func <double, double>)(a => a), false, true);

            AstBuilder astBuilder = new AstBuilder(functionRegistry, true);
            Operation  operation  = astBuilder.Build(tokens);

            Operation optimizedFuction = optimizer.Optimize(operation, functionRegistry, null);

            Assert.AreEqual(typeof(Function), optimizedFuction.GetType());
            Assert.AreEqual(typeof(IntegerConstant), ((Function)optimizedFuction).Arguments[0].GetType());
        }
Пример #24
0
        public void BeginStatement_WhenGivenToken_PushesStatementNode()
        {
            // Arrange:
            var token = new Token {
                TokenKind = TokenKind.String, Image = "<S>"
            };
            var stack = new Stack <IAstNode>();

            stack.Push(_nodeFactoryMock.Object.Create(AstNodeType.Syntax, token));
            var builder = new AstBuilder(_nodeFactoryMock.Object, _prodInfoFactoryMock.Object, stack, _tracerMock.Object);

            // Act:
            builder.BeginStatement(token);

            // Assert:
            Assert.That(stack.Count, Is.EqualTo(2));
            Assert.That(stack.Peek(), Is.InstanceOf(typeof(IStatementNode)));
            Assert.That((stack.Peek() as IStatementNode)?.ProdName, Is.EqualTo(token.Image));
        }
Пример #25
0
        private void FixGeneratedType()
        {
            var d = new DecompilerContext(DestinationType.Module);

            d.CurrentType = DestinationType;
            var visitor = new ObservableAstVisitor();

            visitor.EnterInvocationExpression += exp => {
                var target       = exp.Target;
                var methodInvoke = exp.Annotation <MethodReference>();
                if (methodInvoke == null)
                {
                    return;
                }
                for (var i = 0; i < exp.Arguments.Count; i++)
                {
                    var arg       = exp.Arguments.ToList()[i];
                    var argType   = arg.Annotation <TypeInformation>().InferredType;
                    var param     = methodInvoke.Parameters[i];
                    var paramType = param.ParameterType;
                    if (argType.IsValueType && !paramType.IsValueType)
                    {
                        var argILRange = arg.Annotation <List <ILRange> >();
                        var insts      = GetInstructions(arg);
                        var inst       = GetInstruction(insts, argILRange[0].To);
                        if (inst.Previous.OpCode.Code != Code.Box)
                        {
                            var box = Instruction.Create(OpCodes.Box, argType);
                            insts.Insert(insts.IndexOf(inst), box);
                            Console.WriteLine("Box inserted! Method Arg " + param.Name + " " + argType + " to " + paramType);
                        }
                    }
                }
            };

            copier.Process();

            var astBuilder = new AstBuilder(d);

            astBuilder.AddType(DestinationType);
            // astBuilder.RunTransformations();
            astBuilder.SyntaxTree.AcceptVisitor(visitor);
        }
Пример #26
0
        void RunTransformsAndGenerateCode(AstBuilder astBuilder, ITextOutput output, DecompilationOptions options, ModuleDefinition module)
        {
            astBuilder.RunTransformations(transformAbortCondition);
            if (options.DecompilerSettings.ShowXmlDocumentation)
            {
                AddXmlDocTransform.Run(astBuilder.SyntaxTree);
            }
            var csharpUnit = astBuilder.SyntaxTree;

            csharpUnit.AcceptVisitor(new NRefactory.CSharp.InsertParenthesesVisitor()
            {
                InsertParenthesesForReadability = true
            });
            var unit             = csharpUnit.AcceptVisitor(new CSharpToVBConverterVisitor(new ILSpyEnvironmentProvider()), null);
            var outputFormatter  = new VBTextOutputFormatter(output);
            var formattingPolicy = new VBFormattingOptions();

            unit.AcceptVisitor(new OutputVisitor(outputFormatter, formattingPolicy), null);
        }
Пример #27
0
        public void TestTopologicalSortForGraph2()
        {
            // The connections of CBNs are
            //
            //      +----> 2
            //     /
            //   1 ----> 3
            //     \ 
            //      +----> 4
            //
            string openPath = Path.Combine(TestDirectory, @"core\astbuilder\multioutputs.dyn");

            OpenModel(openPath);

            var id1 = "654c9a4b-3f58-4f90-9bde-c3e615100b12";
            var id2 = "8a55ca22-4424-4ccb-bd2f-3fe79bbeaccf";
            var id3 = "189689be-815b-4a6e-89cb-45b495962cca";
            var id4 = "918ac1ed-98fa-457d-bdb7-fe7456ea3fb5";

            var nodes = CurrentDynamoModel.CurrentWorkspace.Nodes.ToList();

            var shuffle = new ShuffleUtil <NodeModel>(nodes);

            for (int i = 0; i < shuffleCount; ++i)
            {
                var sortedNodes = AstBuilder.TopologicalSortForGraph(shuffle.ShuffledList).ToList();
                Assert.AreEqual(sortedNodes.Count(), 4);

                List <string> ids = sortedNodes.Select(node => node.GUID.ToString()).ToList();

                var nodePosMap = new Dictionary <string, int>();
                for (int idx = 0; idx < ids.Count; ++idx)
                {
                    nodePosMap[ids[idx]] = idx;
                }

                // no matter the order of the input nodes, these invariants
                // should hold
                Assert.IsTrue(nodePosMap[id2] > nodePosMap[id1]);
                Assert.IsTrue(nodePosMap[id3] > nodePosMap[id1]);
                Assert.IsTrue(nodePosMap[id4] > nodePosMap[id1]);
            }
        }
Пример #28
0
        /// <summary>Parse the address formula.</summary>
        /// <param name="addressFormula">The address formula.</param>
        /// <returns>The result of the parsed address or <see cref="IntPtr.Zero"/>.</returns>
        public IntPtr ParseAddress(string addressFormula)
        {
            Contract.Requires(addressFormula != null);

            var reader = new TokenReader();
            var tokens = reader.Read(addressFormula);

            var astBuilder = new AstBuilder();
            var operation  = astBuilder.Build(tokens);

            if (operation == null)
            {
                return(IntPtr.Zero);
            }

            var interpreter = new Interpreter();

            return(interpreter.Execute(operation, this));
        }
Пример #29
0
        public void TestBuildFormula2()
        {
            IFunctionRegistry registry = new MockFunctionRegistry();

            AstBuilder builder   = new AstBuilder(registry);
            Operation  operation = builder.Build(new List <Token>()
            {
                new Token()
                {
                    Value = 2, TokenType = TokenType.Integer
                },
                new Token()
                {
                    Value = '+', TokenType = TokenType.Operation
                },
                new Token()
                {
                    Value = 8, TokenType = TokenType.Integer
                },
                new Token()
                {
                    Value = '*', TokenType = TokenType.Operation
                },
                new Token()
                {
                    Value = 3, TokenType = TokenType.Integer
                }
            });

            Addition       addition       = (Addition)operation;
            Multiplication multiplication = (Multiplication)addition.Argument2;

#if !NETCORE
            Assert.AreEqual(2, ((Constant <int>)addition.Argument1).Value);
            Assert.AreEqual(8, ((Constant <int>)multiplication.Argument1).Value);
            Assert.AreEqual(3, ((Constant <int>)multiplication.Argument2).Value);
#else
            Assert.Equal(2, ((Constant <int>)addition.Argument1).Value);
            Assert.Equal(8, ((Constant <int>)multiplication.Argument1).Value);
            Assert.Equal(3, ((Constant <int>)multiplication.Argument2).Value);
#endif
        }
Пример #30
0
        public void TestTopologicalSortForGraph3()
        {
            // The connections of CBNs are
            //
            //   1 ----+
            //          \
            //   2 ----> 4
            //          /
            //   3 ----+
            //
            var    model    = ViewModel.Model;
            string openPath = Path.Combine(TestDirectory, @"core\astbuilder\multiinputs.dyn");

            ViewModel.OpenCommand.Execute(openPath);
            var nodes = model.CurrentWorkspace.Nodes.ToList();

            int shuffleCount = 10;
            var shuffle      = new ShuffleUtil <NodeModel>(nodes);

            for (int i = 0; i < shuffleCount; ++i)
            {
                var sortedNodes = AstBuilder.TopologicalSortForGraph(shuffle.ShuffledList).ToList();
                Assert.AreEqual(sortedNodes.Count(), 4);

                List <int> nickNames = sortedNodes.Select(node => Int32.Parse(node.NickName)).ToList();

                Dictionary <int, int> nodePosMap = new Dictionary <int, int>();
                for (int idx = 0; idx < nickNames.Count; ++idx)
                {
                    nodePosMap[nickNames[idx]] = idx;
                }

                // no matter input nodes in whatever order, there invariants
                // should hold
                Assert.IsTrue(nodePosMap[1] < nodePosMap[4]);
                Assert.IsTrue(nodePosMap[2] < nodePosMap[4]);
                Assert.IsTrue(nodePosMap[3] < nodePosMap[4]);
                Assert.IsTrue(nodePosMap[1] < nodePosMap[2]);
                Assert.IsTrue(nodePosMap[2] < nodePosMap[3]);
                Assert.IsTrue(nodePosMap[3] < nodePosMap[4]);
            }
        }
Пример #31
0
        void Test(string source, string expectedResult)
        {
            Name.Init( );
            SystemEnvironment.Init( );
            try
            {
                Tokenizer lexer = new Tokenizer(new StringReader(source), "AstTest.cs/sample code");

                System.Text.StringBuilder sb = new System.Text.StringBuilder();

                bool addSpace = false;
                do
                {
                    Syntax result = SyntaxParser.Parse(lexer);

                    if (result == null)
                    {
                        break;
                    }

                    var env = new Environment(SystemEnvironment.Top, EName.None, true);
                    var ast = AstBuilder.Expand(result, env);

                    if (addSpace)
                    {
                        sb.Append(" ");
                    }
                    else
                    {
                        addSpace = true;
                    }
                    sb.Append(Inspector.InspectObject(ast.GetDatum()));
                } while (lexer.LastToken != null);
                string sresult = sb.ToString();
                Assert.AreEqual(expectedResult, sresult);
            }
            catch (BaseSchemeError ex)
            {
                Debug.LogError(string.Format("{0}\n{1}\n{2}", source, ex.Message, ex.StackTrace));
            }
            Name.DeInit( );
        }
Пример #32
0
        IEnumerable <Tuple <string, string> > WriteCodeFilesInProject(AssemblyDefinition assembly, DecompilationOptions options, HashSet <string> directories)
        {
            var files = assembly.MainModule.Types.Where(t => IncludeTypeWhenDecompilingProject(t, options)).GroupBy(
                delegate(TypeDefinition type)
            {
                string file = TextView.DecompilerTextView.CleanUpName(type.Name) + this.FileExtension;
                if (string.IsNullOrEmpty(type.Namespace))
                {
                    return(file);
                }
                else
                {
                    string dir = TextView.DecompilerTextView.CleanUpName(type.Namespace);
                    if (directories.Add(dir))
                    {
                        Directory.CreateDirectory(Path.Combine(options.SaveAsProjectDirectory, dir));
                    }
                    return(Path.Combine(dir, file));
                }
            }, StringComparer.OrdinalIgnoreCase).ToList();

            AstMethodBodyBuilder.ClearUnhandledOpcodes();
            Parallel.ForEach(
                files,
                new ParallelOptions {
                MaxDegreeOfParallelism = Environment.ProcessorCount
            },
                delegate(IGrouping <string, TypeDefinition> file)
            {
                using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, file.Key)))
                {
                    AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.MainModule);
                    foreach (TypeDefinition type in file)
                    {
                        codeDomBuilder.AddType(type);
                    }
                    RunTransformsAndGenerateCode(codeDomBuilder, new PlainTextOutput(w), options, assembly.MainModule);
                }
            });
            AstMethodBodyBuilder.PrintNumberOfUnhandledOpcodes();
            return(files.Select(f => Tuple.Create("Compile", f.Key)));
        }
Пример #33
0
        void RunTransformsAndGenerateCode(AstBuilder astBuilder, ITextOutput output, DecompilationContext ctx, IAstTransform additionalTransform = null)
        {
            astBuilder.RunTransformations(transformAbortCondition);
            if (additionalTransform != null)
            {
                additionalTransform.Run(astBuilder.SyntaxTree);
            }
            CSharpLanguage.AddXmlDocumentation(langSettings.Settings, astBuilder);
            var csharpUnit = astBuilder.SyntaxTree;

            csharpUnit.AcceptVisitor(new ICSharpCode.NRefactory.CSharp.InsertParenthesesVisitor()
            {
                InsertParenthesesForReadability = true
            });
            var unit             = csharpUnit.AcceptVisitor(new CSharpToVBConverterVisitor(new ILSpyEnvironmentProvider()), null);
            var outputFormatter  = new VBTextOutputFormatter(output);
            var formattingPolicy = new VBFormattingOptions();

            unit.AcceptVisitor(new OutputVisitor(outputFormatter, formattingPolicy), null);
        }
Пример #34
0
        public void BeginFactor_WhenGivenAToken_PushesFactorNode()
        {
            // Arrange:
            var token = new Token {
                TokenKind = TokenKind.String, Image = "<F>"
            };
            var stack = new Stack <IAstNode>();

            stack.Push(_nodeFactoryMock.Object.Create(AstNodeType.Term, token));

            var builder = new AstBuilder(_nodeFactoryMock.Object, null, stack, _tracerMock.Object);

            // Act:
            builder.BeginFactor(token);

            // Assert:
            Assert.That(stack.Count, Is.EqualTo(2));
            Assert.That(stack.Peek(), Is.InstanceOf(typeof(IFactorNode)));
            Assert.That((stack.Peek() as IFactorNode)?.Image, Is.EqualTo(token.Image));
        }
Пример #35
0
        public void TestBuildFormula1()
        {
            AstBuilder builder = new AstBuilder();
            Operation operation = builder.Build(new List<Token>() {
                new Token() { Value = '(', TokenType = TokenType.LeftBracket },
                new Token() { Value = 42, TokenType = TokenType.Integer },
                new Token() { Value = '+', TokenType = TokenType.Operation },
                new Token() { Value = 8, TokenType = TokenType.Integer },
                new Token() { Value = ')', TokenType = TokenType.RightBracket },
                new Token() { Value = '*', TokenType = TokenType.Operation },
                new Token() { Value = 2, TokenType = TokenType.Integer }
            });

            Multiplication multiplication = (Multiplication)operation;
            Addition addition = (Addition)multiplication.Argument1;

            Assert.AreEqual(42, ((Constant<int>)addition.Argument1).Value);
            Assert.AreEqual(8, ((Constant<int>)addition.Argument2).Value);
            Assert.AreEqual(2, ((Constant<int>)multiplication.Argument2).Value);
        }
Пример #36
0
		void RunTransformsAndGenerateCode(AstBuilder astBuilder, ITextOutput output, DecompilationOptions options, ModuleDefinition module)
		{
			astBuilder.RunTransformations(transformAbortCondition);
			if (options.DecompilerSettings.ShowXmlDocumentation) {
				try {
					AddXmlDocTransform.Run(astBuilder.SyntaxTree);
				} catch (XmlException ex) {
					string[] msg = (" Exception while reading XmlDoc: " + ex.ToString()).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
					var insertionPoint = astBuilder.SyntaxTree.FirstChild;
					for (int i = 0; i < msg.Length; i++)
						astBuilder.SyntaxTree.InsertChildBefore(insertionPoint, new CSharp.Comment(msg[i], CSharp.CommentType.Documentation), CSharp.Roles.Comment);
				}
			}
			var csharpUnit = astBuilder.SyntaxTree;
			csharpUnit.AcceptVisitor(new NRefactory.CSharp.InsertParenthesesVisitor() { InsertParenthesesForReadability = true });
			var unit = csharpUnit.AcceptVisitor(new CSharpToVBConverterVisitor(new ILSpyEnvironmentProvider()), null);
			var outputFormatter = new VBTextOutputFormatter(output);
			var formattingPolicy = new VBFormattingOptions();
			unit.AcceptVisitor(new OutputVisitor(outputFormatter, formattingPolicy), null);
		}
Пример #37
0
        public void TestBuildFormula2()
        {
            IFunctionRegistry registry = new MockFunctionRegistry();

            AstBuilder builder = new AstBuilder(registry);
            Operation operation = builder.Build(new List<Token>() {
                new Token() { Value = 2, TokenType = TokenType.Integer },
                new Token() { Value = '+', TokenType = TokenType.Operation },
                new Token() { Value = 8, TokenType = TokenType.Integer },
                new Token() { Value = '*', TokenType = TokenType.Operation },
                new Token() { Value = 3, TokenType = TokenType.Integer }
            });

            Addition addition = (Addition)operation;
            Multiplication multiplication = (Multiplication)addition.Argument2;

            Assert.AreEqual(2, ((Constant<int>)addition.Argument1).Value);
            Assert.AreEqual(8, ((Constant<int>)multiplication.Argument1).Value);
            Assert.AreEqual(3, ((Constant<int>)multiplication.Argument2).Value);
        }
Пример #38
0
        void TypeToString(IDecompilerOutput output, ConvertTypeOptions options, ITypeDefOrRef type, IHasCustomAttribute typeAttributes = null)
        {
            var envProvider = new ILSpyEnvironmentProvider();
            var converter   = new CSharpToVBConverterVisitor(type.Module, envProvider);
            var astType     = AstBuilder.ConvertType(type, new StringBuilder(), typeAttributes, options);

            if (type.TryGetByRefSig() != null)
            {
                output.Write("ByRef", BoxedTextColor.Keyword);
                output.Write(" ", BoxedTextColor.Text);
                if (astType is ICSharpCode.NRefactory.CSharp.ComposedType && ((ICSharpCode.NRefactory.CSharp.ComposedType)astType).PointerRank > 0)
                {
                    ((ICSharpCode.NRefactory.CSharp.ComposedType)astType).PointerRank--;
                }
            }

            var vbAstType = astType.AcceptVisitor(converter, null);

            vbAstType.AcceptVisitor(new OutputVisitor(new VBTextOutputFormatter(output), new VBFormattingOptions()), null);
        }
Пример #39
0
        public void TestTopologicalSortForGraph5()
        {
            // The connections of CBNs are
            //
            // 1 <---- 2 <----> 3 <---- 4
            //
            string openPath = Path.Combine(TestDirectory, @"core\astbuilder\linear.dyn");

            OpenModel(openPath);

            var id1 = "cc78b400-329a-4bd8-be9b-5dd6593b31c0";
            var id2 = "306e67f3-d97c-4be7-aab5-298c8c24ae7b";
            var id3 = "682f2b08-0f11-4248-8b98-a5aff29e5fdf";
            var id4 = "34786660-d4a5-4643-8d08-317eb16ed377";


            var nodes = CurrentDynamoModel.CurrentWorkspace.Nodes.ToList();

            var shuffle = new ShuffleUtil <NodeModel>(nodes);

            for (int i = 0; i < shuffleCount; ++i)
            {
                var sortedNodes = AstBuilder.TopologicalSortForGraph(shuffle.ShuffledList).ToList();
                Assert.AreEqual(sortedNodes.Count(), 4);

                List <string> ids = sortedNodes.Select(node => node.GUID.ToString()).ToList();

                var nodePosMap = new Dictionary <string, int>();
                for (int idx = 0; idx < ids.Count; ++idx)
                {
                    nodePosMap[ids[idx]] = idx;
                }

                // no matter the order of the input nodes, these invariants
                // should hold
                Assert.IsTrue(nodePosMap[id4] < nodePosMap[id3]);
                Assert.IsTrue(nodePosMap[id4] < nodePosMap[id2]);
                Assert.IsTrue(nodePosMap[id3] < nodePosMap[id1]);
                Assert.IsTrue(nodePosMap[id2] < nodePosMap[id1]);
            }
        }
 private static string Decompile(Assemblies.AssemblyDefinition asm, IEnumerable<TypeDefinition> types)
 {
     DecompilerSettings settings = new DecompilerSettings();
     settings.FullyQualifyAmbiguousTypeNames = false;
     var ctx = new DecompilerContext(asm.MainModule) { Settings = settings };
     var decompiler = new AstBuilder(ctx);
     foreach (var t in types)
     {
         decompiler.AddType(t);
     }
     new Helpers.RemoveCompilerAttribute().Run(decompiler.CompilationUnit);
     var output = new StringWriter();
     decompiler.GenerateCode(new PlainTextOutput(output));
     return output.ToString().Trim();
 }
Пример #41
0
        public void TestUnaryMinus()
        {
            IFunctionRegistry registry = new MockFunctionRegistry();

            AstBuilder builder = new AstBuilder(registry);
            Operation operation = builder.Build(new List<Token>() {
                new Token() { Value = 5.3, TokenType = TokenType.FloatingPoint },
                new Token() { Value = '*', TokenType = TokenType.Operation},
                new Token() { Value = '_', TokenType = TokenType.Operation },
                new Token() { Value = '(', TokenType = TokenType.LeftBracket },
                new Token() { Value = 5, TokenType = TokenType.Integer },
                new Token() { Value = '+', TokenType = TokenType.Operation },
                new Token() { Value = 42, TokenType = TokenType.Integer },
                new Token() { Value = ')', TokenType = TokenType.RightBracket },
            });

            Multiplication multiplication = (Multiplication)operation;
            Assert.AreEqual(new FloatingPointConstant(5.3), multiplication.Argument1);

            UnaryMinus unaryMinus = (UnaryMinus)multiplication.Argument2;

            Addition addition = (Addition)unaryMinus.Argument;
            Assert.AreEqual(new IntegerConstant(5), addition.Argument1);
            Assert.AreEqual(new IntegerConstant(42), addition.Argument2);
        }
Пример #42
0
        public void TestVariable()
        {
            IFunctionRegistry registry = new MockFunctionRegistry();

            AstBuilder builder = new AstBuilder(registry);
            Operation operation = builder.Build(new List<Token>() {
                new Token() { Value = 10, TokenType = TokenType.Integer },
                new Token() { Value = '*', TokenType = TokenType.Operation },
                new Token() { Value = "var1", TokenType = TokenType.Text }
            });

            Multiplication multiplication = (Multiplication)operation;

            Assert.AreEqual(new IntegerConstant(10), multiplication.Argument1);
            Assert.AreEqual(new Variable("var1"), multiplication.Argument2);
        }
Пример #43
0
        public void TestSinFunction1()
        {
            IFunctionRegistry registry = new MockFunctionRegistry();

            AstBuilder builder = new AstBuilder(registry);
            Operation operation = builder.Build(new List<Token>() {
                new Token() { Value = "sin", TokenType = TokenType.Text },
                new Token() { Value = '(', TokenType = TokenType.LeftBracket },
                new Token() { Value = 2, TokenType = TokenType.Integer },
                new Token() { Value = ')', TokenType = TokenType.RightBracket }
            });

            Function sineFunction = (Function)operation;
            Assert.AreEqual(new IntegerConstant(2), sineFunction.Arguments.Single());
        }
Пример #44
0
        public void TestSinFunction3()
        {
            IFunctionRegistry registry = new MockFunctionRegistry();

            AstBuilder builder = new AstBuilder(registry);
            Operation operation = builder.Build(new List<Token>() {
                new Token() { Value = "sin", TokenType = TokenType.Text },
                new Token() { Value = '(', TokenType = TokenType.LeftBracket },
                new Token() { Value = 2, TokenType = TokenType.Integer },
                new Token() { Value = '+', TokenType = TokenType.Operation },
                new Token() { Value = 3, TokenType = TokenType.Integer },
                new Token() { Value = ')', TokenType = TokenType.RightBracket },
                new Token() { Value = '*', TokenType = TokenType.Operation },
                new Token() { Value = 4.9, TokenType = TokenType.FloatingPoint }
            });

            Multiplication multiplication = (Multiplication)operation;

            Function sineFunction = (Function)multiplication.Argument1;

            Addition addition = (Addition)sineFunction.Arguments.Single();
            Assert.AreEqual(new IntegerConstant(2), addition.Argument1);
            Assert.AreEqual(new IntegerConstant(3), addition.Argument2);

            Assert.AreEqual(new FloatingPointConstant(4.9), multiplication.Argument2);
        }
Пример #45
0
        public override string GetTooltip(MemberReference member)
        {
            MethodDefinition md = member as MethodDefinition;
            PropertyDefinition pd = member as PropertyDefinition;
            EventDefinition ed = member as EventDefinition;
            FieldDefinition fd = member as FieldDefinition;
            if (md != null || pd != null || ed != null || fd != null)
            {
                AstBuilder b = new AstBuilder(new DecompilerContext(member.Module) { Settings = new DecompilerSettings { UsingDeclarations = false } });
                b.DecompileMethodBodies = false;
                if (md != null)
                    b.AddMethod(md);
                else if (pd != null)
                    b.AddProperty(pd);
                else if (ed != null)
                    b.AddEvent(ed);
                else
                    b.AddField(fd);
                b.RunTransformations();
                foreach (var attribute in b.SyntaxTree.Descendants.OfType<AttributeSection>())
                    attribute.Remove();

                StringWriter w = new StringWriter();
                b.GenerateCode(new PlainTextOutput(w));
                return Regex.Replace(w.ToString(), @"\s+", " ").TrimEnd();
            }

            return base.GetTooltip(member);
        }
Пример #46
0
        public void TestMultiplication()
        {
            IFunctionRegistry registry = new MockFunctionRegistry();

            AstBuilder builder = new AstBuilder(registry);
            Operation operation = builder.Build(new List<Token>() {
                new Token() { Value = 10, TokenType = TokenType.Integer },
                new Token() { Value = '*', TokenType = TokenType.Operation },
                new Token() { Value = 2.0, TokenType = TokenType.FloatingPoint }
            });

            Multiplication multiplication = (Multiplication)operation;

            Assert.AreEqual(new IntegerConstant(10), multiplication.Argument1);
            Assert.AreEqual(new FloatingPointConstant(2.0), multiplication.Argument2);
        }
        private void DecompileSelectedNode()
        {
            if (treeView1.SelectedItem == null
                || !(((TreeViewItem)treeView1.SelectedItem).Tag is TypeDefinition))
            {
                codeTextBox.Blocks.Clear();
                return;
            }

            var ty = (TypeDefinition)(((TreeViewItem)treeView1.SelectedItem).Tag);

            var ctx = new DecompilerContext(ty.Module);
            var astBui = new AstBuilder(ctx);
            astBui.AddType(ty);
            astBui.RunTransformations();
            var outp = new RichTextOutput();
            astBui.GenerateCode(outp);

            //var rn = new Run { Text = outp.ToString() };
            //var pa = new Paragraph();
            //pa.Inlines.Add(rn);

            codeTextBox.Blocks.Clear();
            //codeTextBox.Blocks.Add(pa);

            foreach (var b in outp.GetBlocks())
            {
                codeTextBox.Blocks.Add(b);
            }

            codeTextBox.Selection.Select(codeTextBox.ContentStart, codeTextBox.ContentStart);
        }
Пример #48
0
        public void TestModulo()
        {
            IFunctionRegistry registry = new MockFunctionRegistry();

            AstBuilder builder = new AstBuilder(registry);
            Operation operation = builder.Build(new List<Token>() {
                new Token() { Value = 2.7, TokenType = TokenType.FloatingPoint },
                new Token() { Value = '%', TokenType = TokenType.Operation },
                new Token() { Value = 3, TokenType = TokenType.Integer }
            });

            Modulo modulo = (Modulo)operation;

            Assert.AreEqual(new FloatingPointConstant(2.7), modulo.Dividend);
            Assert.AreEqual(new IntegerConstant(3), modulo.Divisor);
        }
Пример #49
0
        public void TestBuildInvalidFormula5()
        {
            IFunctionRegistry registry = new MockFunctionRegistry();

            AstBuilder builder = new AstBuilder(registry);

            AssertExtensions.ThrowsException<ParseException>(() =>
                {
                    Operation operation = builder.Build(new List<Token>() {
                        new Token() { Value = 42, TokenType = TokenType.Integer, StartPosition = 0 },
                        new Token() { Value = '+', TokenType = TokenType.Operation, StartPosition = 2 },
                        new Token() { Value = 8, TokenType = TokenType.Integer, StartPosition = 3 },
                        new Token() { Value = 5, TokenType = TokenType.Integer, StartPosition = 4 }
                    });
                });
        }
Пример #50
0
        public void TestDivision()
        {
            IFunctionRegistry registry = new MockFunctionRegistry();

            AstBuilder builder = new AstBuilder(registry);
            Operation operation = builder.Build(new List<Token>() {
                new Token() { Value = 10, TokenType = TokenType.Integer },
                new Token() { Value = '/', TokenType = TokenType.Operation },
                new Token() { Value = 2, TokenType = TokenType.Integer }
            });

            Assert.AreEqual(typeof(Division), operation.GetType());

            Division division = (Division)operation;

            Assert.AreEqual(new IntegerConstant(10), division.Dividend);
            Assert.AreEqual(new IntegerConstant(2), division.Divisor);
        }
Пример #51
0
        /// <summary>
        /// This function creates EngineController
        /// </summary>
        /// <param name="libraryServices"> LibraryServices manages builtin libraries and imported libraries.</param>
        /// <param name="geometryFactoryFileName">Path to LibG</param>
        /// <param name="verboseLogging">Bool value, if set to true, enables verbose logging</param>
        public EngineController(LibraryServices libraryServices, string geometryFactoryFileName, bool verboseLogging)
        {
            this.libraryServices = libraryServices;
            libraryServices.LibraryLoaded += LibraryLoaded;
            CompilationServices = new CompilationServices(libraryServices.LibraryManagementCore);

            liveRunnerServices = new LiveRunnerServices(this, geometryFactoryFileName);

            liveRunnerServices.ReloadAllLibraries(libraryServices.ImportedLibraries);
            libraryServices.SetLiveCore(LiveRunnerCore);

            codeCompletionServices = new CodeCompletionServices(LiveRunnerCore);

            astBuilder = new AstBuilder(this);
            syncDataManager = new SyncDataManager();

            VerboseLogging = verboseLogging;
        }
Пример #52
0
        public void TestBuildInvalidFormula3()
        {
            AstBuilder builder = new AstBuilder();

            AssertExtensions.ThrowsException<ParseException>(() =>
                {
                    Operation operation = builder.Build(new List<Token>() {
                        new Token() { Value = '(', TokenType = TokenType.LeftBracket, StartPosition = 0 },
                        new Token() { Value = 42, TokenType = TokenType.Integer, StartPosition = 1 },
                        new Token() { Value = '+', TokenType = TokenType.Operation, StartPosition = 3 },
                        new Token() { Value = 8, TokenType = TokenType.Integer, StartPosition = 4 }
                    });
                });
        }
 public static void Decompile(string path)
 {
     var asm = AssemblyDefinition.ReadAssembly(path);
     var settings = new DecompilerSettings();
     settings.FullyQualifyAmbiguousTypeNames = false;
     var ctx = new DecompilerContext(asm.MainModule) { Settings = settings };
     var decompiler = new AstBuilder(ctx);
     decompiler.AddAssembly(asm);
     new Helpers.RemoveCompilerAttribute().Run(decompiler.CompilationUnit);
     var output = new StringWriter();
     decompiler.GenerateCode(new PlainTextOutput(output));
 }
Пример #54
0
 void AddFieldsAndCtors(AstBuilder codeDomBuilder, TypeDefinition declaringType, bool isStatic)
 {
     foreach (var field in declaringType.Fields)
     {
         if (field.IsStatic == isStatic)
             codeDomBuilder.AddField(field);
     }
     foreach (var ctor in declaringType.Methods)
     {
         if (ctor.IsConstructor && ctor.IsStatic == isStatic)
             codeDomBuilder.AddMethod(ctor);
     }
 }
Пример #55
0
        public void TestMultipleVariable()
        {
            IFunctionRegistry registry = new MockFunctionRegistry();

            AstBuilder builder = new AstBuilder(registry);
            Operation operation = builder.Build(new List<Token>() {
                new Token() { Value = "var1", TokenType = TokenType.Text },
                new Token() { Value = '+', TokenType = TokenType.Operation },
                new Token() { Value = 2, TokenType = TokenType.Integer },
                new Token() { Value = '*', TokenType = TokenType.Operation },
                new Token() { Value = '(', TokenType = TokenType.LeftBracket },
                new Token() { Value = 3, TokenType = TokenType.Integer },
                new Token() { Value = '*', TokenType = TokenType.Operation },
                new Token() { Value = "age", TokenType = TokenType.Text },
                new Token() { Value = ')', TokenType = TokenType.RightBracket }
            });

            Addition addition = (Addition)operation;
            Multiplication multiplication1 = (Multiplication)addition.Argument2;
            Multiplication multiplication2 = (Multiplication)multiplication1.Argument2;

            Assert.AreEqual(new Variable("var1"), addition.Argument1);
            Assert.AreEqual(new IntegerConstant(2), multiplication1.Argument1);
            Assert.AreEqual(new IntegerConstant(3), multiplication2.Argument1);
            Assert.AreEqual(new Variable("age"), multiplication2.Argument2);
        }
Пример #56
0
        public void TestExponentiation()
        {
            IFunctionRegistry registry = new MockFunctionRegistry();

            AstBuilder builder = new AstBuilder(registry);
            Operation operation = builder.Build(new List<Token>() {
                new Token() { Value = 2, TokenType = TokenType.Integer },
                new Token() { Value = '^', TokenType = TokenType.Operation },
                new Token() { Value = 3, TokenType = TokenType.Integer }
            });

            Exponentiation exponentiation = (Exponentiation)operation;

            Assert.AreEqual(new IntegerConstant(2), exponentiation.Base);
            Assert.AreEqual(new IntegerConstant(3), exponentiation.Exponent);
        }
Пример #57
0
 public void TestBuildInvalidFormula5()
 {
     AstBuilder builder = new AstBuilder();
     Operation operation = builder.Build(new List<Token>() {
         new Token() { Value = 42, TokenType = TokenType.Integer, StartPosition = 0 },
         new Token() { Value = '+', TokenType = TokenType.Operation, StartPosition = 2 },
         new Token() { Value = 8, TokenType = TokenType.Integer, StartPosition = 3 },
         new Token() { Value = 5, TokenType = TokenType.Integer, StartPosition = 4 }
     });
 }
Пример #58
0
        public void TestSinFunction2()
        {
            AstBuilder builder = new AstBuilder();
            Operation operation = builder.Build(new List<Token>() {
                new Token() { Value = "sin", TokenType = TokenType.Text },
                new Token() { Value = '(', TokenType = TokenType.LeftBracket },
                new Token() { Value = 2, TokenType = TokenType.Integer },
                new Token() { Value = '+', TokenType = TokenType.Operation },
                new Token() { Value = 3, TokenType = TokenType.Integer },
                new Token() { Value = ')', TokenType = TokenType.RightBracket }
            });

            Function sineFunction = (Function)operation;

            Addition addition = (Addition)sineFunction.Arguments.Single();
            Assert.AreEqual(new IntegerConstant(2), addition.Argument1);
            Assert.AreEqual(new IntegerConstant(3), addition.Argument2);
        }
Пример #59
0
 void RunTransformsAndGenerateCode(AstBuilder astBuilder, ITextOutput output, DecompilationOptions options, IAstTransform additionalTransform = null)
 {
     astBuilder.RunTransformations(transformAbortCondition);
     if (additionalTransform != null)
     {
         additionalTransform.Run(astBuilder.SyntaxTree);
     }
     astBuilder.GenerateCode(output);
 }