Beispiel #1
0
        public List <QubitValueResult> GetQubitResultStatesById(List <IbmJobMeasurmentResult> qubitValueResults, string ResultId)
        {
            var qubitValueResult = (from ms in qubitValueResults where ms.Id == ResultId select ms).FirstOrDefault();

            if (qubitValueResult == null)
            {
                return(new List <QubitValueResult>());
            }
            if (qubitValueResult.Qasms.Count == 0)
            {
                return(new List <QubitValueResult>());
            }
            ProgramParser _parser  = new ProgramParser();
            var           commands = _parser.GetSyntaxList(_parser.GetCommandList(qubitValueResult.Qasms[0].Qasm));
            List <Qubit>  Qubits   = new List <Qubit>();

            foreach (var cmd in commands)
            {
                Measurment casted_cmd = cmd.CommandType as Measurment;
                if (casted_cmd != null)
                {
                    int qubit_index;
                    if (int.TryParse(cmd.Args[1], out qubit_index))
                    {
                        Qubits.Add(new Qubit(null, qubit_index));
                    }
                }
            }
            return(IbmComputer.GetQubitResultStates(qubitValueResult, Qubits));
        }
Beispiel #2
0
        public void ProgramParser_AnotherExample()
        {
            //Arrange
            const string program = @"
                (def apply (func list)
                  (if (empty? list) 
                    (then ()) 
                    (else 
                      (concat 
                        ((func (first list))) 
                        (apply func (rem list))
                      )
                    )
                  )
                )

                (let +1 (lambda (a) (+ a 1)))
                (apply +1 (1 2 3)) ; returns (2 3 4)";

            ProgramParser parser = new ProgramParser();

            //Act
            ProgramNode node = (ProgramNode)parser.Parse(program);

            //Assert
            Assert.AreEqual(3, node.Expressions.Count);
        }
Beispiel #3
0
Datei: Wul.cs Projekt: szensk/wul
        private static bool RunFile(string filePath, Scope scope = null)
        {
            Parser = new ProgramParser(new FileInfo(filePath).FullName);
            try
            {
                WulInterpreter.Interpret(LoadFile(filePath), scope);
            }
            catch (ParseException pe)
            {
                string program = File.ReadLines(filePath).Skip(pe.Line - 1).First();
                Console.WriteLine(program);
                string underline = pe.GetUnderline;
                if (underline != null)
                {
                    Console.WriteLine(underline);
                }
                Console.WriteLine(pe.GetErrorMessage);
                return(false);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error: {e.Message}");
#if DEBUG
                Console.WriteLine(e.StackTrace);
                //TODO fix up traceback line numbers
                //StdLib.Debug.Traceback(Value.EmptyList, null);
#endif
                return(false);
            }
            return(true);
        }
Beispiel #4
0
        // full file name
        public static ProgramNode ParseFile(string fileName)
        {
            ProgramParser parser   = new ProgramParser(fileName);
            string        contents = File.ReadAllText(fileName);

            return(Parse(contents, parser));
        }
Beispiel #5
0
        public void ProgramCollection_GetNumberOfGroups_ReturnsCorrectly()
        {
            var programCollection = ProgramParser.ParseFile("day12testinput.txt");

            var numGroups = programCollection.GetNumberOfGroups();

            Assert.Equal(2, numGroups);
        }
Beispiel #6
0
        public void ProgramCollection_GetConnectedPrograms_ReturnsCorrectly()
        {
            var programCollection = ProgramParser.ParseFile("day12testinput.txt");

            var connected = programCollection.GetConnectedPrograms(0);

            Assert.Equal(6, connected.Count);
        }
Beispiel #7
0
        public void Interpreter_PrintNil()
        {
            ProgramParser parser  = new ProgramParser();
            string        program = "(print nil)";

            ProgramNode node = (ProgramNode)parser.Parse(program);

            WulInterpreter.Interpret(node);
        }
Beispiel #8
0
        public void ProgramParser_EmptyProgram()
        {
            ProgramParser parser  = new ProgramParser();
            string        program = "";

            ProgramNode node = (ProgramNode)parser.Parse(program);

            Assert.AreEqual(0, node.Expressions.Count);
        }
Beispiel #9
0
        public void ProgramParser_TwoExpressions()
        {
            ProgramParser parser  = new ProgramParser();
            string        program = "(print ok) (die)";

            ProgramNode node = (ProgramNode)parser.Parse(program);

            Assert.AreEqual(2, node.Expressions.Count);
        }
Beispiel #10
0
        public void ProgramParser_ListOfOne()
        {
            //Arrange
            const string  program = "(:: System.Console.WriteLine ('ok'))";
            ProgramParser parser  = new ProgramParser();

            //Act
            ProgramNode node = (ProgramNode)parser.Parse(program);

            //Assert
            Assert.AreEqual(1, node.Expressions.Count);
        }
Beispiel #11
0
        public Spooky2Program(string name, string command, double stepSize)
        {
            Name     = name;
            commands = ProgramParser.Parse(command).ToArray();

            // Debug - reconstruct the program.
            var debug = StoredProgramData.SetCommands(commands);

            if (debug != command)
            {
            }
        }
Beispiel #12
0
        public void ProgramParser_LeadingCommentWithParenthesis()
        {
            //Arrange
            const string  program = "; test\r\n; (that is it)\r\n(print 'ok')";
            ProgramParser parser  = new ProgramParser();

            //Act
            ProgramNode node = (ProgramNode)parser.Parse(program);

            //Assert
            Assert.AreEqual(1, node.Expressions.Count);
            Assert.AreEqual(2, node.Expressions.First().Children.Count);
        }
Beispiel #13
0
        public void ProgramParser_CommentWithParenthesis()
        {
            //Arrange
            const string  program = "(defn cos (a) (identity a) \r\n;(that is it)\r\n)";
            ProgramParser parser  = new ProgramParser();

            //Act
            ProgramNode node = (ProgramNode)parser.Parse(program);

            //Assert
            Assert.AreEqual(1, node.Expressions.Count);
            Assert.AreEqual(4, node.Expressions.First().Children.Count);
        }
Beispiel #14
0
        public void ProgramParser_FactorialExample()
        {
            //Arrange
            const string  program = "(defn fact (a)\r\n\t(if (< a 2) \r\n\t\t(then 1) \r\n\t\t(else (* a (fact (- a 1))))\r\n\t)\r\n)";
            ProgramParser parser  = new ProgramParser();

            //Act
            ProgramNode node = (ProgramNode)parser.Parse(program);

            //Assert
            Assert.AreEqual(1, node.Expressions.Count);
            Assert.AreEqual(4, node.Expressions.First().Children.Count);
        }
Beispiel #15
0
        void SimpleProgram()
        {
            var p = ProgramParser.Tokenize("123");

            Assert.Equal(1, p.Count());

            var steps = ProgramParser.Parse("123, 456, M1, B1, B3").ToArray();

            Assert.Equal(5, steps.Length);
            var options = new RunningOptions();

            var durations = steps.Select(s => ((IStep)s).Duration(options)).ToArray();
            var freqs     = steps.Select(s => s.Frequency1.ToHertz(options)).ToArray();
        }
Beispiel #16
0
        public void Give_accumulator_before_the_program_run_an_instruction_a_second_time(
            string programDescription,
            int expectedAccumulatorValue)
        {
            // Given
            var program = ProgramParser.Parse(programDescription);

            // When
            var(actualAccumulatorValue, _, isInfiniteLoop) = IsolatedProgramRunner.Execute(program);

            // Then
            Assert.Equal(expectedAccumulatorValue, actualAccumulatorValue);
            Assert.True(isInfiniteLoop);
        }
        public void Fix_program_and_give_terminates_program_accumulator(
            string infiniteLoopProgramDescription,
            int expectedAccumulator)
        {
            // Given
            var infiniteLoopProgram = ProgramParser.Parse(infiniteLoopProgramDescription);

            // When
            var fixedProgram    = ProgramFixer.Fix(infiniteLoopProgram);
            var executionResult = IsolatedProgramRunner.Execute(fixedProgram);

            // Then
            Assert.Equal(expectedAccumulator, executionResult.AccumulatorValue);
        }
Beispiel #18
0
        public void Give_accumulator_after_the_program_terminates(
            string programDescription,
            int expectedAccumulatorValue)
        {
            // Given
            var program = ProgramParser.Parse(programDescription);

            // When
            var(actualAccumulatorValue, isProgramTerminates, _) = IsolatedProgramRunner.Execute(program);

            // Then
            Assert.Equal(expectedAccumulatorValue, actualAccumulatorValue);
            Assert.True(isProgramTerminates);
        }
Beispiel #19
0
        public ProgramVM(ObservableCollection <ProgramInfo> programList, List <CameraInfo> camInfoList, ObservableCollection <CameraNameWrapper> cameraNameList, List <PresetParams> presettingList)
        {
            _ea = Notification.Instance;
            this.programList    = programList;
            this.cameraNameList = cameraNameList;
            camList             = camInfoList;
            presetList          = presettingList;
            modeColors          = ModeColors.Singleton(_ea);
            writer = new ProgramParser(constant.PROGRAM_FILE);
            List <CameraCommand> list = new List <CameraCommand>();

            save(-1);
            _ea.GetEvent <ProgramSaveEvent>().Subscribe(save);
        }
        public void Fix_infinite_loop_program_by_switching_only_one_instruction(
            string infiniteLoopProgramDescription,
            string expectedTerminableProgramDescription)
        {
            // Given
            var infiniteLoopProgram  = ProgramParser.Parse(infiniteLoopProgramDescription);
            var expectedFixedProgram = ProgramParser.Parse(expectedTerminableProgramDescription);

            // When
            var actualFixedProgram = ProgramFixer.Fix(infiniteLoopProgram);
            var executionResult    = IsolatedProgramRunner.Execute(actualFixedProgram);

            // Then
            Assert.Equal(expectedFixedProgram, actualFixedProgram);
            Assert.True(executionResult.IsProgramTerminates);
        }
Beispiel #21
0
        public void ProgramParser_CommentWithStartingParenthesis()
        {
            //Arrange
            const string program = "(defn test ()\r\n"
                                   + "   ;(unpack\r\n"
                                   + "        (?? 1 2)\r\n"
                                   + "    ;)\r\n"
                                   + ")\r\n";
            ProgramParser parser = new ProgramParser();

            //Act
            ProgramNode node = (ProgramNode)parser.Parse(program);

            //Assert
            Assert.AreEqual(1, node.Expressions.Count);
            Assert.AreEqual(4, node.Expressions.First().Children.Count);
        }
Beispiel #22
0
        public void ProgramParser_SimpleExample()
        {
            ProgramParser parser  = new ProgramParser();
            const string  program = @"
                (def fact (a) (
                    (if (< a 2) 
                      (then 1)
                      (else (fact (- a 1)))
                    )
                  )
                )

                (print (fact 10))";

            ProgramNode node = (ProgramNode)parser.Parse(program);

            Assert.AreEqual(2, node.Expressions.Count);
        }
Beispiel #23
0
        /// <summary>
        ///		Gemera la documentación
        /// </summary>
        private void GenerateDocuments()
        {
            if (ValidateData())
            {
                DocumentFileModelCollection objColDocuments;
                ProgramModel objProgram = new ProgramParser().ParseSolution(fnSolution.FileName);

                // Borra el directorio destino
                Bau.Libraries.LibHelper.Files.HelperFiles.KillPath(pthTarget.PathName);
                // Genera la documentación
                objColDocuments = new DocumentationGenerator(GetParametersDocuments(), pthTarget.PathName).Process(objProgram);
                // Muestra la documentación
                txtLog.Text = objColDocuments.Debug(0);
                // Muestra los nodos
                trvNodes.Nodes.Clear();
                ShowDocumentNodes(objColDocuments, null);
                trvNodes.ExpandAll();
            }
        }
Beispiel #24
0
        public void ProgramParser_CommentExample()
        {
            //Arrange
            const string program = @"
                (defn add (a b c)
                  (+ a b) ; this adds the first two arguments
                )

                (print add)
                (print (dump add))";

            ProgramParser parser = new ProgramParser();

            //Act
            ProgramNode node = (ProgramNode)parser.Parse(program);

            //Assert
            Assert.AreEqual(3, node.Expressions.Count);
        }
Beispiel #25
0
        public void ReturnNoExpressionTest()
        {
            const string Code = @"
            Return;
            ";

            ProgramNode program = MyAssert.NoError(() =>
            {
                var lexemes = new Lexer(Code).LexAll();
                var parser  = new ProgramParser(lexemes, Code);
                return(parser.ParseWholeProgram());
            });

            Assert.NotNull(program);
            Assert.AreEqual(1, program !.TopLevelStatementNodes.Count);
            Assert.IsTrue(program.TopLevelStatementNodes[0] is ReturnStatementNode
            {
                ReturnExpressionNode: null
            });
Beispiel #26
0
Datei: Wul.cs Projekt: szensk/wul
        private static bool RunString(string input, Scope scope = null)
        {
            Parser = new ProgramParser("stdin");
            Scope currentScope = scope ?? Global.Scope.EmptyChildScope();

            try
            {
                var programNode = (ProgramNode)Parser.Parse(input);
                var result      = WulInterpreter.Interpret(programNode, currentScope);
                if (result != null && result.Any())
                {
                    foreach (var item in result)
                    {
                        if (ReferenceEquals(item, Value.Nil) && result.Count == 1)
                        {
                            continue;
                        }
                        var args = new List <IValue> {
                            item is WulString ? new WulString($"'{item.AsString()}'") : item
                        };
                        IO.Print(args, Global.Scope);
                    }
                }
                return(true);
            }
            catch (ParseException pe)
            {
                string underline = pe.GetUnderline;
                if (underline != null)
                {
                    Console.WriteLine(underline);
                }
                Console.WriteLine(pe.GetErrorMessage);
                return(false);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error: {e.Message}");
                System.Diagnostics.Debug.WriteLine(e.StackTrace);
                return(false);
            }
        }
Beispiel #27
0
        public void FunctionDeclarationNoParametersWithReturnTest()
        {
            const string Code = @"
            Func HelloWorld() As Int
            {
                Output(""Hello "" + x);
            }
            ";

            FunctionDeclarationNode func = MyAssert.NoError(() =>
            {
                var lexemes = new Lexer(Code).LexAll();
                var parser  = new ProgramParser(lexemes, Code);
                return(parser.ParseFunctionDeclaration());
            });

            Assert.NotNull(func);
            Assert.AreEqual("HelloWorld", func !.Identifier);
            Assert.AreEqual(0, func.ParameterNodes.Count);
            Assert.NotNull(func.ReturnTypeNode);
            Assert.AreEqual(1, func.BodyNode.Count);
        }
Beispiel #28
0
        public List <QubitValueResult> GetQubitResultStates(IbmJobMeasurmentResult qubitValueResult)
        {
            if (qubitValueResult.Qasms.Count == 0)
            {
                return(new List <QubitValueResult>());
            }
            ProgramParser _parser  = new ProgramParser();
            var           commands = _parser.GetSyntaxList(_parser.GetCommandList(qubitValueResult.Qasms[0].Qasm));
            List <Qubit>  Qubits   = new List <Qubit>();

            foreach (var cmd in commands)
            {
                Measurment casted_cmd = cmd.CommandType as Measurment;
                if (casted_cmd != null)
                {
                    int qubit_index;
                    if (int.TryParse(cmd.Args[1], out qubit_index))
                    {
                        Qubits.Add(new Qubit(null, qubit_index));
                    }
                }
            }
            return(IbmComputer.GetQubitResultStates(qubitValueResult, Qubits));
        }
Beispiel #29
0
        public void AddExpressionSpecialTestAST()
        {
            // Source file to produce an AST from
            string source = System.IO.File.ReadAllText(AppContext.BaseDirectory + "/Testfiles/tang/AddExpression.tang");

            // File path relative to where the debug file is located which is in a land far, far away
            Lexer l = new Lexer(File.ReadAllText(AppContext.BaseDirectory + "../../../../../../docs/tang.tokens.json"));

            // Call the Analyse method from the Lexical Analysis class
            var tokens = l.Analyse(source);

            // Initialise a program parser
            ProgramParser parser = new ProgramParser();

            // Convert tokens to Parsing.Data.Token
            var tokenEnumerator = tokens.Select(t => new Parsing.Data.Token()
            {
                Name = t.Name, Value = t.Value
            }).GetEnumerator();

            tokenEnumerator.MoveNext();

            // Produce a parse tree by calling the ParseProgram method
            var parseTree = parser.ParseProgram(tokenEnumerator);

            // Create a new instance of the ProgramToASTTranslator class
            var astTranslator = new Translation.ProgramToAST.ProgramToASTTranslator();

            // Use the ProgramToASTTranslator with parseTree as parameter to get the AST
            AST.Data.AST ast = astTranslator.TranslatetoAST(parseTree) as AST.Data.AST;

            // Below is a hardcoded tree of how the AST is expected to look
            var astExpected = new AST.Data.AST(true)
            {
                new AST.Data.GlobalStatement(true)
                {
                    new AST.Data.Statement(true)
                    {
                        new AST.Data.IntegerDeclarationInit(true)
                        {
                            new AST.Data.IntType(true)
                            {
                                new AST.Data.Token()
                                {
                                    Name = "int8"
                                }
                            },
                            new AST.Data.Token()
                            {
                                Name = "identifier"
                            },
                            new AST.Data.Token()
                            {
                                Name = "="
                            },
                            new AST.Data.IntegerExpression(true)
                            {
                                new AST.Data.AddExpression(true)
                                {
                                    new AST.Data.IntegerExpression(true)
                                    {
                                        new AST.Data.AddExpression(true)
                                        {
                                            new AST.Data.IntegerExpression(true)
                                            {
                                                new AST.Data.Token()
                                                {
                                                    Name = "numeral"
                                                }
                                            },
                                            new AST.Data.Token()
                                            {
                                                Name = "+"
                                            },
                                            new AST.Data.IntegerExpression(true)
                                            {
                                                new AST.Data.Token()
                                                {
                                                    Name = "numeral"
                                                }
                                            }
                                        }
                                    },
                                    new AST.Data.Token()
                                    {
                                        Name = "+"
                                    },
                                    new AST.Data.IntegerExpression(true)
                                    {
                                        new AST.Data.Token()
                                        {
                                            Name = "numeral"
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                new AST.Data.Token()
                {
                    Name = "eof"
                }
            };


            // Call a method to walk the tree's nodes and test if their names are equal
            TreeAsserter(ast, astExpected);
        }
Beispiel #30
0
        public void ConvertToASTCorrectly()
        {
            /* Alias.tang file:
             * int8 a
             * a = 2
             * int8 b
             * b = a
             * tokens:
             * int8 identifier newline
             * identifier = numeral newline
             * int8 identifier newline
             * identifier = identifier newline eof
             */

            // When running the method ParseProgram on an enumerator of these tokens, the result is a big parse tree
            // The goal of the ProgramToASTTranslator is to take this parse tree as input and output an AST
            // The AST output is written by hand from the .tang file, and then it is asserted if the output is equivalent to the expected output

            string source = System.IO.File.ReadAllText(AppContext.BaseDirectory + "/Testfiles/tang/Alias.tang");

            // File path relative to where the debug file is located which is in a land far, far away
            Lexer l = new Lexer(File.ReadAllText(AppContext.BaseDirectory + "../../../../../../docs/tang.tokens.json"));

            var           tokens          = l.Analyse(source);
            ProgramParser parser          = new ProgramParser();
            var           tokenEnumerator = tokens.Select(t => new Parsing.Data.Token()
            {
                Name = t.Name, Value = t.Value
            }).GetEnumerator();

            tokenEnumerator.MoveNext();
            var parseTree = parser.ParseProgram(tokenEnumerator);

            // Create a new instance of the ProgramToASTTranslator class
            var astTranslator = new Translation.ProgramToAST.ProgramToASTTranslator();

            // Use the ProgramToASTTranslator with parseTree as parameter to get the AST
            AST.Data.AST ast = astTranslator.TranslatetoAST(parseTree) as AST.Data.AST;

            // Below is a hardcoded tree of how the AST is expected to look
            var astExpected = new AST.Data.AST(true)
            {
                new AST.Data.GlobalStatement(true)
                {
                    new AST.Data.CompoundGlobalStatement(true)
                    {
                        new AST.Data.GlobalStatement(true)
                        {
                            new AST.Data.Statement(true)
                            {
                                new AST.Data.IntegerDeclaration(true)
                                {
                                    new AST.Data.IntType(true)
                                    {
                                        new AST.Data.Token()
                                        {
                                            Name = "int8"
                                        }
                                    },
                                    new AST.Data.Token()
                                    {
                                        Name = "identifier"
                                    }
                                }
                            }
                        },
                        new AST.Data.Token()
                        {
                            Name = "newline"
                        },
                        new AST.Data.GlobalStatement(true)
                        {
                            new AST.Data.CompoundGlobalStatement(true)
                            {
                                new AST.Data.GlobalStatement(true)
                                {
                                    new AST.Data.Statement(true)
                                    {
                                        new AST.Data.IntegerAssignment(true)
                                        {
                                            new AST.Data.Token()
                                            {
                                                Name = "identifier"
                                            },
                                            new AST.Data.Token()
                                            {
                                                Name = "="
                                            },
                                            new AST.Data.IntegerExpression(true)
                                            {
                                                new AST.Data.Token()
                                                {
                                                    Name = "numeral"
                                                }
                                            }
                                        }
                                    }
                                },
                                new AST.Data.Token()
                                {
                                    Name = "newline"
                                },
                                new AST.Data.GlobalStatement(true)
                                {
                                    new AST.Data.CompoundGlobalStatement(true)
                                    {
                                        new AST.Data.GlobalStatement(true)
                                        {
                                            new AST.Data.Statement(true)
                                            {
                                                new AST.Data.IntegerDeclaration(true)
                                                {
                                                    new AST.Data.IntType(true)
                                                    {
                                                        new AST.Data.Token()
                                                        {
                                                            Name = "int8"
                                                        }
                                                    },
                                                    new AST.Data.Token()
                                                    {
                                                        Name = "identifier"
                                                    }
                                                }
                                            }
                                        },
                                        new AST.Data.Token()
                                        {
                                            Name = "newline"
                                        },
                                        new AST.Data.GlobalStatement(true)
                                        {
                                            new AST.Data.Statement(true)
                                            {
                                                new AST.Data.IntegerAssignment(true)
                                                {
                                                    new AST.Data.Token()
                                                    {
                                                        Name = "identifier"
                                                    },
                                                    new AST.Data.Token()
                                                    {
                                                        Name = "="
                                                    },
                                                    new AST.Data.IntegerExpression(true)
                                                    {
                                                        new AST.Data.Token()
                                                        {
                                                            Name = "identifier"
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    },
                },
                new AST.Data.Token()
                {
                    Name = "eof"
                }
            };

            // Call a method to walk the tree's nodes and test if their names are equal
            TreeAsserter(ast, astExpected);
        }