public void ParseInputTest()
        {
            string input          = $"5 5{Environment.NewLine}1 2 N{Environment.NewLine}LMLMLMLMM{Environment.NewLine}3 3 E{Environment.NewLine}MMRMMRMRRM{Environment.NewLine}";
            string output         = string.Empty;
            string expectedOutput = $"1 3 N{Environment.NewLine}5 1 E{Environment.NewLine}";

            //poor man's dependency injection
            IInstructionParser parser  = new InstructionParser();
            IRoverFactory      factory = new RoverFactory();
            IRoverService      service = new RoverService(factory, parser);

            var response = service.ParseInput(new Domain.Parser.Messages.ExecuteRequest()
            {
                Input = input
            });

            //if no exceptions encountered
            if (response.Exception == null)
            {
                //get the output
                output = response.Output;
            }
            else
            {
                output = response.Exception.Message;
            }

            Console.WriteLine(output);
            Assert.AreEqual(expectedOutput, output);
        }
        public void DecompileCommand(UInt160 contractHash)
        {
            var script = _scriptTable.GetScript(contractHash.ToArray(), false);

            if (script == null)
            {
                throw (new ArgumentNullException("Contract not found"));
            }

            var parser = new InstructionParser();

            foreach (var i in parser.Parse(script))
            {
                _consoleWriter.Write(i.Location.ToString() + " ", ConsoleOutputStyle.Information);

                if (i is InstructionWithPayload ip)
                {
                    _consoleWriter.Write(i.OpCode.ToString() + " ");
                    _consoleWriter.WriteLine("{" + ip.Payload.ToHexString(true) + "}", ConsoleOutputStyle.DarkGray);
                }
                else
                {
                    _consoleWriter.WriteLine(i.OpCode.ToString());
                }
            }
        }
        public void ExecuteInstructions()
        {
            var stringWriter = new StringWriter();

            Console.SetOut(stringWriter);
            var instructions = new List <string>
            {
                "6 3",
                "1 2 N",
                "LMLMLMLMM",
                "3 3 E",
                "MMRMMRMRRM",
                "1 2 N",
                "LMLMLMLMM",
                "1 9 N",
                "LRLRMMMRL"
            };
            var roverPaths = InstructionParser.Parse(instructions);

            InstructionParser.Execute(roverPaths);

            Plateau.RoverAtPosition(new Position(1, 3)).Should().Be(true);

            /*
             * stringWriter.ToString().Should().Be(
             *  "1 3 N\r\n" +
             *  "5 1 E\r\n" +
             *  "1 3 N CRASHED\r\n" +
             *  "1 9 N CRASHED\r\n");
             */
        }
Beispiel #4
0
        /// <summary>
        /// Executes the translation.
        /// </summary>
        /// <param name="paths">The paths.</param>
        /// <param name="extensionProgress">If <c>true</c>, periodically write progress to console
        /// if the input binaries are adequately large.</param>
        /// <returns>The computed cfg and type environment.</returns>
        public static (Cfg, TypeEnvironment) ExecuteTranslation(string[] paths,
                                                                bool extensionProgress = false)
        {
            (var assemblies, var totalSize) = GetAssemblies(paths);

            InstructionParser.RegisterAllKnownParsers();

            var reportProgressExtension = totalSize > 1e7 && extensionProgress;

            var decompilationService = new DecompilationService(assemblies, reportProgressExtension);
            var tenvParser           = new TenvParserService(reportProgressExtension);
            var cfgParser            = new CfgParserService(reportProgressExtension);

            var result = decompilationService
                         .Execute()
                         .ThenExecute(tenvParser)
                         .ThenExecute(cfgParser);

            var tenv = result.GetResult <TenvParserResult>().TypeEnvironment;
            var cfg  = result.GetResult <CfgParserResult>().Cfg;

            Log.PrintAllUnknownInstruction();
            Log.WriteLine();
            Log.PrintCoverageStats(result.GetResult <CfgParserResult>().Methods);

            return(cfg, tenv);
        }
Beispiel #5
0
        private void btnSendCommands_Click(object sender, EventArgs e)
        {
            StringBuilder allResults = new StringBuilder();

            try
            {
                var builder = new PlanetBuilder();
                IParser parser = new InstructionParser();
                PlanetDescription planetDescription = parser.Parse(tbCommands.Text);
                Queue<Robot> robots = builder.BuildPlanet(planetDescription);

                while (robots.Count > 0)
                {
                    Robot robot = robots.Dequeue();
                    robot.ExecuteCommands();
                    string result = String.Format("{0} {1} {2}{3}", robot.CurrentPosition.X,
                    robot.CurrentPosition.Y, robot.CurrentOrientation.ToString()[0], ((robot.IsLost) ? " LOST" : ""));

                    allResults.Append(result.Trim() + "\r\n");
                }

            }
            catch (MartianException ex)
            {
                allResults.Append(ex.Message + "\r\n");
            }
            catch (Exception ex)
            {
                allResults.Append("Unhandled Exception: " + ex.Message + "\r\n");
            }
            tbResult.Text = allResults.ToString();
        }
Beispiel #6
0
        /// <summary>
        /// Executes the translation.
        /// </summary>
        /// <param name="paths">The paths.</param>
        /// <param name="printprocs">The printprocs.</param>
        /// <returns></returns>
        public static (Cfg, TypeEnvironment) ExecuteTranslation(string[] paths,
                                                                string printprocs = null)
        {
            var assemblies = GetAssemblies(paths);

            InstructionParser.RegisterAllKnownParsers();

            var decompilationService = new DecompilationService(assemblies);
            var tenvParser           = new TenvParserService();
            var cfgParser            = new CfgParserService();

            var result = decompilationService
                         .Execute()
                         .ThenExecute(tenvParser)
                         .ThenExecute(cfgParser);

            var tenv = result.GetResult <TenvParserResult>().TypeEnvironment;
            var cfg  = result.GetResult <CfgParserResult>().Cfg;

            if (printprocs != null)
            {
                PrintCfg(cfg, printprocs);
            }

            Log.PrintAllUnknownInstruction();
            Log.WriteLine();
            Log.PrintCoverageStats(result.GetResult <CfgParserResult>().Methods);

            return(cfg, tenv);
        }
Beispiel #7
0
        public void SamplePart2()
        {
            var   program = InstructionParser.ParseProgram(_programTest1);
            Day08 day8    = new Day08();

            day8.ExecutePart2(program).Should().Be(8);
        }
        public void Part2_WithSampleInput_ShouldReturn8()
        {
            string sampleInput = @"nop +0
                acc +1
                jmp +4
                acc +3
                jmp -3
                acc -99
                acc +1
                jmp -4
                acc +6";

            string[] programData = new List <string>(
                sampleInput.Split(Environment.NewLine,
                                  StringSplitOptions.TrimEntries |
                                  StringSplitOptions.RemoveEmptyEntries
                                  )
                )
                                   .ToArray();

            Computer computer = new Computer(new string[0]);

            for (int i = 0; i < programData.Length; i++)
            {
                programData = new List <string>(
                    sampleInput.Split(Environment.NewLine,
                                      StringSplitOptions.TrimEntries |
                                      StringSplitOptions.RemoveEmptyEntries
                                      )
                    )
                              .ToArray();
                InstructionParser parser         = new InstructionParser(programData[i]);
                string            newInstruction = string.Empty;

                if (parser.Command == "nop")
                {
                    newInstruction = "jmp " + parser.Value.ToString("+#;-#;+0");
                }
                else if (parser.Command == "jmp")
                {
                    newInstruction = "nop " + parser.Value.ToString("+#;-#;+0");
                }
                else
                {
                    continue;
                }

                programData[i] = newInstruction;
                computer       = new Computer(programData);
                computer.Run();

                if (!computer.IsInfiniteLoop)
                {
                    break;
                }
            }

            Assert.Equal(8, computer.Accumulator);
        }
Beispiel #9
0
        public string Solve(string[] input)
        {
            var parser       = new InstructionParser();
            var instructions = input.Select(line => parser.Parse(line));
            var layout       = new SwarmScript(instructions).Compile();

            return((layout.Outputs[0] * layout.Outputs[1] * layout.Outputs[2]).ToString());
        }
        public void Parse_ShouldParseCharacterToEnum(char inputValue, Instruction expectedValue)
        {
            var parser = new InstructionParser();

            var result = parser.Parse(inputValue);

            result.Should().Be(expectedValue);
        }
Beispiel #11
0
        public void RowRotationGetsParsed()
        {
            var parser = new InstructionParser();
            var parsed = parser.Parse("rotate row y=0 by 4");
            var proper = new Instruction(Instruction.Operation.RowRotation, 0, 4);

            Assert.Equal(proper, parsed);
        }
Beispiel #12
0
        public void RectangleGetsParsed()
        {
            var parser = new InstructionParser();
            var parsed = parser.Parse("rect 3x2");
            var proper = new Instruction(Instruction.Operation.Rectangle, 3, 2);

            Assert.Equal(proper, parsed);
        }
Beispiel #13
0
        public void SamplePart1()
        {
            var      program = InstructionParser.ParseProgram(_programTest1);
            Computer p       = new Computer(program);

            p.ExecuteStopWhenLoop();
            p.GetAcc().Should().Be(5);
        }
Beispiel #14
0
        public void TestParser(string input, Direction expectedDirection, int expectedNumber)
        {
            var instructions = InstructionParser.ParseInstructions(input);

            var(direction, number) = Assert.Single(instructions) !;
            Assert.Equal(expectedDirection, direction);
            Assert.Equal(expectedNumber, number);
        }
Beispiel #15
0
        public void ColumnRotationGetsParsed()
        {
            var parser = new InstructionParser();
            var parsed = parser.Parse("rotate column x=14 by 31");
            var proper = new Instruction(Instruction.Operation.ColRotation, 14, 31);

            Assert.Equal(proper, parsed);
        }
        void TestParseInstruction <T>(byte[] byteCode, IComparable <T> expected) where T : class
        {
            Int16 instructionCode = BitConverter.ToInt16(byteCode);
            InstructionConfiguratorStub configurator = new InstructionConfiguratorStub();
            InstructionParser           parser       = new InstructionParser(configurator);
            var parsed = parser.Parse(instructionCode) as T;

            Assert.Equal(0, expected.CompareTo(parsed));
        }
Beispiel #17
0
        public string Solve(string[] input)
        {
            var parser       = new InstructionParser();
            var instructions = input.Select(line => parser.Parse(line));
            var layout       = new SwarmScript(instructions).Compile();
            var bot          = layout.Bots.Values.Single(b => b.Values.Max() == 61 && b.Values.Min() == 17);

            return(bot.Id.ToString());
        }
        void TestInvalidInstructionCall(byte[] byteCode)
        {
            Int16 instructionCode = BitConverter.ToInt16(byteCode);
            InstructionConfiguratorStub configurator = new InstructionConfiguratorStub();
            InstructionParser           parser       = new InstructionParser(configurator);

            parser.UnknownInstructionFoundEvent += (Int16 code) => throw new InvalidInstructionException();
            Assert.Throws <InvalidInstructionException>(() => parser.Parse(instructionCode));
        }
        public string Solve(string[] input)
        {
            var registers = new RegisterMap(new[] { 'a', 'b', 'c', 'd' });
            var parser    = new InstructionParser(registers);
            var interpret = new Interpreter(registers);

            interpret.Execute(input.Select(i => parser.Parse(i)).ToArray());
            return(interpret.Registers[0].ToString());
        }
Beispiel #20
0
        private IEnumerable <Instruction> ConvertToNodes(Stream stream)
        {
            var reader            = new XmlCompatibilityReader(stream);
            var runtimeTypeSource = RuntimeTypeSource;
            var pullParser        = new InstructionParser(runtimeTypeSource);
            var protoParser       = new ProtoInstructionParser(runtimeTypeSource);

            return(pullParser.Parse(protoParser.Parse(reader)).ToList());
        }
Beispiel #21
0
        private ICentralProcessingUnit BuildCPU(IArithmeticLogicUnit alu, IMemoryManagementUnit mmu, ISystemBridge bridge)
        {
            IInstructionConfigurator configurator = new InstructionConfigurator(bridge);
            IInstructionParser       parser       = new InstructionParser(configurator);
            InstructionReader        reader       = new InstructionReader(mmu, alu.IP);
            ICentralProcessingUnit   cpu          = new CentralProcessingUnit(alu, parser, reader);

            return(cpu);
        }
Beispiel #22
0
        public string Solve(string[] input)
        {
            var parser       = new InstructionParser();
            var instructions = input.Select(parser.Parse);
            var simulator    = new ScreenSimulator(50, 6);
            var endState     = instructions.Aggregate(simulator.InitialState(),
                                                      (state, instruction) => simulator.Simulate(instruction, state));

            return(endState.ToString());
        }
        private ICollection <Instruction> ExtractNodesFromPullParser(string xml)
        {
            var pullParser = new InstructionParser(RuntimeTypeSource);

            using (var stream = new StringReader(xml))
            {
                var reader = new XmlCompatibilityReader(stream);
                return(pullParser.Parse(new ProtoInstructionParser(RuntimeTypeSource).Parse(reader)).ToList());
            }
        }
Beispiel #24
0
 void EnsureInstructionsParsed()
 {
     if (m_instructions == null && m_pRow->RVA != 0)
     {
         var header       = GetMethodHeader();
         var instructions = InstructionParser.Parse(new BufferWrapper(header.RawHeader + header.Size, header.CodeSize), this);
         #pragma warning disable 420
         Interlocked.CompareExchange(ref m_instructions, instructions, null);
         #pragma warning restore 420
     }
 }
Beispiel #25
0
        public void Part2ReturnsExpectedResult(string[] puzzleInput, int expectedResult)
        {
            // Arrange
            InstructionParser sut = new InstructionParser();

            // Act
            int stepsToEscape = sut.Part2(puzzleInput);

            // Assert
            Assert.That(stepsToEscape, Is.EqualTo(expectedResult));
        }
Beispiel #26
0
        public Property InputInstructionGetsParsed()
        {
            var inputInstructions = from value in Arb.Generate <byte>()
                                    from bot in Arb.Generate <byte>()
                                    select new { value, bot, instruction = $"value {value} goes to bot {bot}" };
            var parser  = new InstructionParser();
            var parsing = inputInstructions.Select(i => new { original = i, parsed = parser.Parse(i.instruction) as InputInstruction });

            return(Prop.ForAll(parsing.ToArbitrary(),
                               p => p.parsed != null && p.parsed.Value == p.original.value && p.parsed.Bot == p.original.bot));
        }
        public string Solve(string[] input)
        {
            var parser       = new InstructionParser();
            var instructions = input.Select(parser.Parse);
            var simulator    = new ScreenSimulator(50, 6);
            var endState     = instructions.Aggregate(simulator.InitialState(),
                                                      (state, instruction) => simulator.Simulate(instruction, state));
            int pixelsLit = endState.Pixels.Cast <bool>().Count(pixel => pixel);

            return(pixelsLit.ToString());
        }
Beispiel #28
0
        public void Example1(string input, int distance)
        {
            var instructions = InstructionParser.ParseInstructions(input.Replace("|", Environment.NewLine));
            var ship         = new Ship(FacingDirection.East, new Position());

            foreach (var instruction in instructions)
            {
                ship = ship.PerformInstruction(instruction);
            }

            Assert.Equal(distance, ship.GetManhanttanDistance());
        }
Beispiel #29
0
        public void SolvePuzzle1()
        {
            var input = new FileReader()
                        .GetResource("AdventOfCode2020.Tests.Day12.PuzzleInput.txt");

            var instructions = InstructionParser.ParseInstructions(input);
            var ship         = new Ship(FacingDirection.East, new Position());

            ship = instructions.Aggregate(ship, (current, instruction) => current.PerformInstruction(instruction));

            _testOutputHelper.WriteLine(ship.GetManhanttanDistance().ToString());
        }
Beispiel #30
0
        private static IEnumerable <Instruction> ReadNodes(Type underlyingType)
        {
            var resourceProvider = new InflatableTranslator();

            using (var stream = resourceProvider.GetInflationSourceStream(underlyingType))
            {
                var reader            = new XmlCompatibilityReader(stream);
                var runtimeTypeSource = new WpfRuntimeTypeSource();
                var loader            = new InstructionParser(runtimeTypeSource);
                var protoParser       = new ProtoInstructionParser(runtimeTypeSource);

                return(loader.Parse(protoParser.Parse(reader)));
            }
        }
Beispiel #31
0
        public void Example2(string input, int distance)
        {
            var instructions = InstructionParser.ParseInstructions(input.Replace("|", Environment.NewLine));
            var waypoint     = new Waypoint(FacingDirection.East, new Position {
                Horizontal = 10, Vertical = 1
            });
            var ship = new WaypointShip(FacingDirection.East, new Position(), waypoint);

            foreach (var instruction in instructions)
            {
                ship = ship.PerformInstruction(instruction);
            }

            Assert.Equal(distance, ship.GetManhanttanDistance());
        }
Beispiel #32
0
        public void TestFromFiles()
        {
            foreach (TestDescription description in Tests)
            {
                IParser parser = new InstructionParser();
                PlanetDescription planetDescription = parser.Parse(description.Test);
                Queue<Robot> robots = new PlanetBuilder().BuildPlanet(planetDescription);

                StringBuilder allResults = new StringBuilder();

                while (robots.Count > 0)
                {
                    Robot robot = robots.Dequeue();
                    robot.ExecuteCommands();
                    string result = String.Format("{0} {1} {2}{3}", robot.CurrentPosition.X,
                        robot.CurrentPosition.Y, robot.CurrentOrientation.ToString()[0], ((robot.IsLost) ? " LOST" : ""));

                    allResults.Append(result.Trim()+"\r\n");
                }

                Assert.AreEqual(allResults.ToString().Trim(), description.ExpectedResult.Trim());
            }
        }
Beispiel #33
0
        private static IEnumerable<Instruction> ReadNodes(Type underlyingType)
        {
            var resourceProvider = new InflatableTranslator();

            using (var stream = resourceProvider.GetInflationSourceStream(underlyingType))
            {
                var reader = new XmlCompatibilityReader(stream);
                var runtimeTypeSource = new WpfRuntimeTypeSource();
                var loader = new InstructionParser(runtimeTypeSource);
                var protoParser = new ProtoInstructionParser(runtimeTypeSource);

                return loader.Parse(protoParser.Parse(reader));
            }
        }