public void Compiler_Execute_AllOfTheValidSampleKleinPrograms()
        {
            var folder = Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\KleinPrograms\Programs\fullprograms");
            var files  = Directory.GetFiles(folder, "*.kln");

            Assert.That(files.Length, Is.GreaterThan(0));

            foreach (var file in files)
            {
                var input    = File.ReadAllText(file);
                var frontEnd = new FrontEnd();
                var program  = frontEnd.Compile(input);
                Assert.That(program, Is.Not.Null, frontEnd.ErrorRecord.ToString());
                var tacs   = new ThreeAddressCodeFactory().Generate(program);
                var output = new CodeGenerator().Generate(tacs);

                foreach (var testDatum in TestDatum.GetTestData(input))
                {
                    Console.WriteLine($"{Path.GetFileName(file)}      {testDatum}");
                    var tinyOut = new TinyMachine(ExePath, TestFilePath).Execute(output, testDatum.Args);
                    Console.WriteLine(tinyOut);
                    Assert.That(tinyOut, Is.EquivalentTo(testDatum.Asserts), Path.GetFileName(file));
                }
            }
        }
Exemple #2
1
            public void Compile([NotNull] string mainZilFile)
            {
                var compiler = new FrontEnd();

                compiler.CheckingFilePresence += (sender, e) =>
                {
                    e.Exists = inputs.ContainsKey(e.FileName);
                };

                compiler.OpeningFile += (sender, e) =>
                {
                    if (e.Writing)
                    {
                        e.Stream = outputs[e.FileName] = new MemoryStream();
                    }
                    else
                    {
                        if (inputs.TryGetValue(e.FileName, out var content))
                        {
                            var result = new MemoryStream();
                            using (var wtr = new StreamWriter(result, Encoding.UTF8, 512, true))
                            {
                                wtr.Write(content);
                                wtr.Flush();
                            }
                            result.Position = 0;
                            e.Stream        = result;
                        }
                    }
                };

                var compilationResult = compiler.Compile(mainZilFile, Path.ChangeExtension(mainZilFile, ".zap"));

                Assert.IsTrue(compilationResult.Success, "Compilation failed");
            }
Exemple #3
1
        public void NestedFunctionCalls_ShouldWorkCorrectly()
        {
            // Test Visit Function Call

            // arrange
            var input = @"main() : integer
                              secondary()
                          secondary() : integer
                              tertiary()
                          tertiary() : integer
                              17";

            var frontEnd = new FrontEnd();
            var program  = frontEnd.Compile(input);

            Assert.That(program, Is.Not.Null, frontEnd.ErrorRecord.ToString());

            // act
            var tacs    = new ThreeAddressCodeFactory().Generate(program);
            var output  = new CodeGenerator().Generate(tacs);
            var tinyOut = new TinyMachine(ExePath, TestFilePath).Execute(output);

            // assert
            Assert.That(tinyOut, Is.EqualTo(new[] { "17" }));
        }
Exemple #4
0
        public void ParserErrors_Compiler_ShouldProduceCorrectErrorMessages(string filename, string message)
        {
            var file     = Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\KleinPrograms\Programs\parser", filename);
            var frontEnd = new FrontEnd();

            frontEnd.Compile(File.ReadAllText(file));
            var error = frontEnd.ErrorRecord;

            Assert.That(error.ErrorType, Is.Not.EqualTo(ErrorTypeEnum.No));
            Assert.That(error.ToString(), Is.EqualTo(message));
        }
Exemple #5
0
        protected override void ProcessRecord()
        {
            var frontEnd = new FrontEnd();
            var program  = frontEnd.Compile(File.ReadAllText(Path));

            if (program == null)
            {
                var exceptionMessage = $"{Path}{frontEnd.ErrorRecord}";
                throw new Exception(exceptionMessage);
            }
            WriteObject(program);
        }
Exemple #6
0
        public void CompileTest()
        {
            var failed = new List <(string Path, string Message)>(
                Directory.GetFiles(SourceDir, "*.rk").MapParallelAll(src =>
            {
                var filename = Path.GetFileName(src);
                var txt      = File.ReadAllText(src);
                var lines    = txt.SplitLine();
                var il       = Path.Combine(ObjDir, Path.GetFileNameWithoutExtension(src) + ".il");
                try
                {
                    FrontEnd.Compile(new StringReader(txt), il, new string[] { "System.Runtime" });

                    var valid = GetLineContent(lines, "###start", "###end");
                    if (!valid.Found)
                    {
                        return(filename, "test code not found ###start - ###end");
                    }
                    var il_src = File.ReadAllText(il).Trim();

                    if (valid.Text.Trim() != il_src)
                    {
                        return(filename, "il make a difference");
                    }
                }
                catch (Exception ex)
                {
                    var error = GetLineContent(lines, "###error", "###end");
                    if (!error.Found || error.Text.Trim() != ex.Message)
                    {
                        return(filename, ex.Message);
                    }
                    File.WriteAllText(il, $@"
.assembly {filename} {{}}
.method public static void main()
{{
    .entrypoint
    ret
}}
");
                }
                return(filename, "");
            }).Where(x => x.Item2 != ""));

            if (failed.Count > 0)
            {
                Assert.Fail(failed.Map(x => $"{x.Path}: {x.Message}").Join("\n"));
            }
        }
Exemple #7
0
        public void Or_IfBothAreFalse_ShouldReturn0()
        {
            // arrange
            var input = @"main() : boolean
                              false or false";

            var frontEnd = new FrontEnd();
            var program  = frontEnd.Compile(input);

            Assert.That(program, Is.Not.Null, frontEnd.ErrorRecord.ToString());

            // act
            var tacs    = new ThreeAddressCodeFactory().Generate(program);
            var output  = new CodeGenerator().Generate(tacs);
            var tinyOut = new TinyMachine(ExePath, TestFilePath).Execute(output);

            // assert
            Assert.That(tinyOut, Is.EqualTo(new[] { "0" }));
        }
Exemple #8
0
        public void And_LeftAndRightAreTrue_AndReturn1()
        {
            // arrange
            var input = @"main() : boolean
                              true and true";

            var frontEnd = new FrontEnd();
            var program  = frontEnd.Compile(input);

            Assert.That(program, Is.Not.Null, frontEnd.ErrorRecord.ToString());

            // act
            var tacs    = new ThreeAddressCodeFactory().Generate(program);
            var output  = new CodeGenerator().Generate(tacs);
            var tinyOut = new TinyMachine(ExePath, TestFilePath).Execute(output);

            // assert
            Assert.That(tinyOut, Is.EqualTo(new[] { "1" }));
        }
Exemple #9
0
        public void Equality_IfTheNumbersAreTheSame_1_ShouldBeReturned()
        {
            // arrange
            var input = @"main() : boolean
                              2 = 2";

            var frontEnd = new FrontEnd();
            var program  = frontEnd.Compile(input);

            Assert.That(program, Is.Not.Null, frontEnd.ErrorRecord.ToString());

            // act
            var tacs    = new ThreeAddressCodeFactory().Generate(program);
            var output  = new CodeGenerator().Generate(tacs);
            var tinyOut = new TinyMachine(ExePath, TestFilePath).Execute(output);

            // assert
            Assert.That(tinyOut, Is.EqualTo(new[] { "1" }));
        }
Exemple #10
0
        public void AllArithmaticTogether_ShouldNestAndAll_ThatAndMiraculouslyWork()
        {
            // arrange
            var input = @"main(n : integer, m : integer) : integer
                              -(n-1)/2 * (m+1)";

            var frontEnd = new FrontEnd();
            var program  = frontEnd.Compile(input);

            Assert.That(program, Is.Not.Null, frontEnd.ErrorRecord.ToString());

            // act
            var tacs    = new ThreeAddressCodeFactory().Generate(program);
            var output  = new CodeGenerator().Generate(tacs);
            var tinyOut = new TinyMachine(ExePath, TestFilePath).Execute(output, "9 11");

            // assert
            Assert.That(tinyOut, Is.EqualTo(new[] { "-48" }));
        }
Exemple #11
0
        public void Compiler_ShouldCompile_AllOfMyPrograms()
        {
            var  folder  = Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\KleinPrograms");
            var  files   = Directory.GetFiles(folder, "*.kln");
            bool allPass = true;
            var  result  = new StringBuilder();

            foreach (var file in files)
            {
                var input    = File.ReadAllText(file);
                var frontEnd = new FrontEnd();
                if (frontEnd.Compile(input) == null)
                {
                    allPass = false;
                    result.AppendLine($"{Path.GetFileName(file)}{frontEnd.ErrorRecord.FilePosition} {frontEnd.ErrorRecord}");
                }
            }
            ConsoleWriteLine.If(allPass != true, result.ToString());
            Assert.That(allPass, Is.True);
        }
Exemple #12
0
        public void TheValueReturnedFromMain_ShouldBeSentToStdOut()
        {
            // Tests Visit Program, Definition, Body and IntegerLiteral

            // arrange
            var input = @"main() : integer
                              1";

            var frontEnd = new FrontEnd();
            var program  = frontEnd.Compile(input);

            Assert.That(program, Is.Not.Null, frontEnd.ErrorRecord.ToString());

            // act
            var tacs = new ThreeAddressCodeFactory().Generate(program);

            Console.WriteLine(tacs);
            // assert
            Assert.That(tacs.ToString(), Is.EqualTo(@"
Init 0  
BeginCall main 0 t0
t0 := Call main 
BeginCall print 1 t1
Param t0  
t1 := Call print 
Halt   

BeginFunc print 1
PrintVariable arg0  
EndFunc print  

BeginFunc main 0
t0 := 1
Return t0  
EndFunc main  
"));
            var output  = new CodeGenerator().Generate(tacs);
            var tinyOut = new TinyMachine(ExePath, TestFilePath).Execute(output);

            Assert.That(tinyOut, Is.EqualTo(new[] { "1" }));
        }
Exemple #13
0
        public void Negate_ShouldNegateTheVariable()
        {
            // Tests Visit Negate

            // arrange
            var input = @"main(n : integer) : integer
                              -n";

            var frontEnd = new FrontEnd();
            var program  = frontEnd.Compile(input);

            Assert.That(program, Is.Not.Null, frontEnd.ErrorRecord.ToString());

            // act
            var tacs    = new ThreeAddressCodeFactory().Generate(program);
            var output  = new CodeGenerator().Generate(tacs);
            var tinyOut = new TinyMachine(ExePath, TestFilePath).Execute(output, "19");

            // assert
            Assert.That(tinyOut, Is.EqualTo(new[] { "-19" }));
        }
Exemple #14
0
        public void PrintExpressions_ProgramShouldSendTheirValueToStdOut()
        {
            // Tests Visit Print

            // arrange
            var input = @"main() : integer
                              print(1)
                              1";

            var frontEnd = new FrontEnd();
            var program  = frontEnd.Compile(input);

            Assert.That(program, Is.Not.Null, frontEnd.ErrorRecord.ToString());

            // act
            var tacs    = new ThreeAddressCodeFactory().Generate(program);
            var output  = new CodeGenerator().Generate(tacs);
            var tinyOut = new TinyMachine(ExePath, TestFilePath).Execute(output);

            // assert
            Assert.That(tinyOut, Is.EqualTo(new[] { "1", "1" }));
        }
Exemple #15
0
        public void IfThenElse_IfConditionFalse_ElseBranchShouldExecute()
        {
            // arrange
            var input = @"main() : integer
                              if false then
                                  17
                               else
                                  19";

            var frontEnd = new FrontEnd();
            var program  = frontEnd.Compile(input);

            Assert.That(program, Is.Not.Null, frontEnd.ErrorRecord.ToString());

            // act
            var tacs = new ThreeAddressCodeFactory().Generate(program);

            Console.WriteLine(tacs);
            var output  = new CodeGenerator().Generate(tacs);
            var tinyOut = new TinyMachine(ExePath, TestFilePath).Execute(output);

            // assert
            Assert.That(tinyOut, Is.EqualTo(new[] { "19" }));
        }
Exemple #16
0
        public void ArgumentsShouldBePassedThrouh_NestedFunctionCalls()
        {
            // Tests Visit FunctionCall and Identifier
            // arrange
            var input = @"main(n : integer) : integer
                              secondary(n)
                          secondary(n: integer) : integer
                              tertiary(n)
                          tertiary(n : integer) : integer
                              n";

            var frontEnd = new FrontEnd();
            var program  = frontEnd.Compile(input);

            Assert.That(program, Is.Not.Null, frontEnd.ErrorRecord.ToString());

            // act
            var tacs    = new ThreeAddressCodeFactory().Generate(program);
            var output  = new CodeGenerator().Generate(tacs);
            var tinyOut = new TinyMachine(ExePath, TestFilePath).Execute(output, "19");

            // assert
            Assert.That(tinyOut, Is.EqualTo(new[] { "19" }));
        }