Ejemplo n.º 1
0
        public void TestStructMultipleDeclarations()
        {
            var diagnosticsMock = new Moq.Mock <IDiagnostics>();
            var diagnostics     = diagnosticsMock.Object;

            var aDecl1 = new StructDeclaration(
                null,
                "A",
                new List <StructField>()
            {
            });
            var aDecl2 = new StructDeclaration(
                null,
                "A",
                new List <StructField>()
            {
            });

            var program = new Program(
                null,
                new List <StructDeclaration>()
            {
                aDecl1, aDecl2
            },
                new List <FunctionDeclaration>()
            {
            });

            Assert.ThrowsException <NameResolverException>(() => this.nameResolver.Run(program, diagnostics));

            MockDiagnostics.Verify(
                diagnosticsMock,
                NameResolver.MultipleDeclarationsDiagnostic,
                NameResolver.MultipleDeclarationsDiagnostic);
        }
Ejemplo n.º 2
0
        public void TestFunctionRedeclaration()
        {
            var f = new FunctionDeclaration(
                new Range(new StringLocation(0), new StringLocation(1)),
                "f",
                UnitType.Instance,
                new List <VariableDeclaration>(),
                new InstructionBlock(new Range(new StringLocation(0), new StringLocation(1)), new List <Expression>()),
                false);

            var f2 = new FunctionDeclaration(
                new Range(new StringLocation(0), new StringLocation(1)),
                "f",
                UnitType.Instance,
                new List <VariableDeclaration>(),
                new InstructionBlock(new Range(new StringLocation(0), new StringLocation(1)), new List <Expression>()),
                false);

            var diagnosticsMock = new Moq.Mock <IDiagnostics>();
            var diagnostics     = diagnosticsMock.Object;

            var resolver  = new NameResolver();
            var functions = new List <FunctionDeclaration> {
                f, f2
            };
            var root = new Program(
                new Range(new StringLocation(0), new StringLocation(1)),
                new List <StructDeclaration>(),
                functions);

            Assert.ThrowsException <NameResolverException>(() => this.nameResolver.Run(root, diagnostics));
            MockDiagnostics.Verify(diagnosticsMock, NameResolver.MultipleDeclarationsDiagnostic);
        }
Ejemplo n.º 3
0
        public void PositiveExamples(IKjuExample example)
        {
            var diag = new Mock <IDiagnostics>();

            Compiler.RunOnInputReader(example.Program, diag.Object);
            MockDiagnostics.Verify(diag, example.ExpectedMagicStrings.ToArray());
        }
Ejemplo n.º 4
0
        public void Test5TokenNotToken()
        {
            var dfa   = new Mock <IDfa <DummyTokens?, char> >();
            var lexer = new Lexer <DummyTokens?>(dfa.Object, DummyTokens.Eof);

            dfa.Setup(x => x.StartingState()).Returns(this.states[0]);
            var trans0 = new Dictionary <char, IState>
            {
                ['a'] = this.states[1], ['b'] = this.states[2], [EndOfInput] = this.states[2]
            };
            var trans1 = new Dictionary <char, IState>
            {
                ['a'] = this.states[2], ['b'] = this.states[2], [EndOfInput] = this.states[2]
            };

            dfa.Setup(x => x.Transitions(this.states[0])).Returns(trans0);
            dfa.Setup(x => x.Transitions(this.states[1])).Returns(trans1);
            dfa.Setup(x => x.Transitions(this.states[2])).Returns(trans1);
            dfa.Setup(x => x.IsStable(this.states[2])).Returns(true);
            dfa.Setup(x => x.Label(this.states[1])).Returns(DummyTokens.A);
            foreach (char c in trans0.Keys)
            {
                dfa.Setup(x => x.Transition(this.states[0], c)).Returns(trans0[c]);
            }

            foreach (char c in trans1.Keys)
            {
                dfa.Setup(x => x.Transition(this.states[1], c)).Returns(trans1[c]);
            }

            var diag = new Mock <IDiagnostics>();

            Assert.ThrowsException <LexerException>(() => lexer.Scan(StringToLetters("ab"), diag.Object).ToList());
            MockDiagnostics.Verify(diag, Lexer <DummyTokens?> .NonTokenDiagnostic);
        }
Ejemplo n.º 5
0
        public void TestParseException()
        {
            var rules = new Dictionary <Label, IDfa <Optional <Rule <Label> >, Label> >();
            var dfa   = new IntDfa();

            rules.Add(Label.A, dfa);
            var grammar = new CompiledGrammar <Label>()
            {
                Rules = rules, StartSymbol = Label.A
            };
            var parseTable =
                new Dictionary <Tuple <IDfa <Optional <Rule <Label> >, Label>, IState, Label>, ParseAction <Label> >
            {
                {
                    new Tuple <IDfa <Optional <Rule <Label> >, Label>, IState, Label>(dfa, new IntState(0), Label.B),
                    new ParseAction <Label>()
                    {
                        Kind = ParseAction <Label> .ActionKind.Shift
                    }
                }
            };
            var parser = new Parser <Label>(grammar, parseTable);

            var tokens = new List <Token <Label> > {
                new Token <Label>()
                {
                    Category = Label.B
                }
            };
            var diag = new Moq.Mock <IDiagnostics>();

            Assert.ThrowsException <ParseException>(() => parser.Parse(tokens, diag.Object));
            MockDiagnostics.Verify(diag, Parser <Label> .PrematureEofDiagnosticType);
        }
Ejemplo n.º 6
0
        public void TestStructSameFieldName()
        {
            var diagnosticsMock = new Moq.Mock <IDiagnostics>();
            var diagnostics     = diagnosticsMock.Object;

            var declA = new StructDeclaration(
                null,
                "A",
                new List <StructField>()
            {
                new StructField(null, "x", IntType.Instance),
                new StructField(null, "x", BoolType.Instance),
            });

            var program = new Program(
                null,
                new List <StructDeclaration>()
            {
                declA
            },
                new List <FunctionDeclaration>()
            {
            });

            Assert.ThrowsException <NameResolverException>(() => this.nameResolver.Run(program, diagnostics));

            MockDiagnostics.Verify(
                diagnosticsMock,
                NameResolver.MultipleDeclarationsDiagnostic);
        }
Ejemplo n.º 7
0
        public void TestStructWithBuilinTypeName()
        {
            var diagnosticsMock = new Moq.Mock <IDiagnostics>();
            var diagnostics     = diagnosticsMock.Object;

            var intDecl1 = new StructDeclaration(
                null,
                "Int",
                new List <StructField>()
            {
            });
            var program = new Program(
                null,
                new List <StructDeclaration>()
            {
                intDecl1
            },
                new List <FunctionDeclaration>()
            {
            });

            Assert.ThrowsException <NameResolverException>(() => this.nameResolver.Run(program, diagnostics));

            MockDiagnostics.Verify(
                diagnosticsMock,
                NameResolver.TypeIdentifierErrorDiagnosticsType);
        }
Ejemplo n.º 8
0
        public void NegativeExamples(IKjuExample example)
        {
            var diag = new Mock <IDiagnostics>();

            Assert.ThrowsException <CompilerException>(() => Compiler.RunOnInputReader(example.Program, diag.Object));

            MockDiagnostics.Verify(diag, example.ExpectedMagicStrings.ToArray());
        }
Ejemplo n.º 9
0
        public void CheckPositive(string data, params string[] diagTypes)
        {
            var diagnosticsMock = new Mock <IDiagnostics>();
            var diagnostics     = diagnosticsMock.Object;

            KjuCompilerUtils.MakeAstWithReturnsChecked(data, diagnostics);
            MockDiagnostics.Verify(diagnosticsMock, diagTypes);
        }
Ejemplo n.º 10
0
        public void TestPreprocessInputNotMatchedCommentEnd()
        {
            string s    = "/*/ OK, fixed now */*/";
            var    diag = new Mock <IDiagnostics>();

            Assert.ThrowsException <PreprocessorException>(() =>
                                                           FromPreprocessor(this.preprocessor.PreprocessInput(ToInput(s), diag.Object)));
            MockDiagnostics.Verify(diag, Preprocessor.UnexpectedCommentEndDiagnosticType);
        }
Ejemplo n.º 11
0
        public void TestPreprocessInputInfiniteComment()
        {
            string s    = "/*/* No problem here :^) */*";
            var    diag = new Mock <IDiagnostics>();

            Assert.ThrowsException <PreprocessorException>(() =>
                                                           FromPreprocessor(this.preprocessor.PreprocessInput(ToInput(s), diag.Object)));
            MockDiagnostics.Verify(diag, Preprocessor.UnterminatedCommentDiagnosticType);
        }
Ejemplo n.º 12
0
        public void IndirectVariableAccessTest()
        {
            string program         = @"
                fun kju (param : Int) : Unit {
                    var x : Int;
                    fun f (par1 : Int, par2 : Int) : Int {
                        x;
                        return par1;
                    };
                    fun g () : Unit {
                        f(1, 2);
                    };
                    g();
                }";
            var    diagnosticsMock = new Mock <IDiagnostics>();
            var    diagnostics     = diagnosticsMock.Object;
            var    ast             = KjuCompilerUtils.MakeAstWithLinkedNames(program, diagnostics);
            var    identifiersMap  = this.CreateIdDictionary(ast);
            var    functions       = identifiersMap
                                     .Where(p => p.Value is FunctionDeclaration)
                                     .ToDictionary(p => p.Key, p => p.Value as FunctionDeclaration);
            var variables = identifiersMap
                            .Where(p => p.Value is VariableDeclaration)
                            .ToDictionary(p => p.Key, p => p.Value as VariableDeclaration);
            var mockCallGraph = new Mock <ICallGraphGenerator>();
            var callGraphDict = new Dictionary <FunctionDeclaration, IReadOnlyCollection <FunctionDeclaration> >
            {
                [functions["kju"]] = new HashSet <FunctionDeclaration>()
                {
                    functions["f"]
                },
                [functions["f"]] = new HashSet <FunctionDeclaration>(),
                [functions["g"]] = new HashSet <FunctionDeclaration>()
                {
                    functions["f"]
                },
            };

            mockCallGraph.Setup(foo => foo.BuildCallGraph(It.IsAny <Node>())).Returns(callGraphDict);

            var nodeInfoExtractors = new Dictionary <VariableInfo, INodeInfoExtractor>
            {
                [VariableInfo.Access]        = new AccessInfoExtractor(),
                [VariableInfo.Modifications] = new ModifyInfoExtractor(),
            };

            VariableAccessGraphGenerator tempQualifier =
                new VariableAccessGraphGenerator(mockCallGraph.Object, nodeInfoExtractors);
            INodeInfoExtractor infoExtractor = new AccessInfoExtractor();
            var graph = VariableAccessGraphGenerator.TransitiveCallClosure(mockCallGraph.Object, ast, infoExtractor);

            Assert.IsTrue(graph[functions["kju"]].Contains(variables["x"]));
            Assert.IsTrue(graph[functions["kju"]].Contains(variables["par1"]));
            Assert.IsTrue(graph[functions["g"]].Contains(variables["x"]));
            Assert.IsTrue(graph[functions["g"]].Contains(variables["par1"]));
            MockDiagnostics.Verify(diagnosticsMock);
        }
Ejemplo n.º 13
0
        public void TestParensUnmatched()
        {
            var    parser = BuildParenParser();
            string parens = "(()";

            var diag = new Mock <IDiagnostics>();

            Assert.ThrowsException <ParseException>(() => parser.Parse(GetParenTokens(parens), diag.Object));
            MockDiagnostics.Verify(diag, Parser <ParenAlphabet> .UnexpectedSymbolDiagnosticType);
        }
Ejemplo n.º 14
0
        public void CheckNegative(string data, params string[] diagTypes)
        {
            var diagnosticsMock = new Mock <IDiagnostics>();
            var diagnostics     = diagnosticsMock.Object;

            Assert.ThrowsException <ReturnCheckerException>(() =>
            {
                KjuCompilerUtils.MakeAstWithReturnsChecked(data, diagnostics);
            });
            MockDiagnostics.Verify(diagnosticsMock, diagTypes);
        }
Ejemplo n.º 15
0
        public void AssignmentLhsNotVariable()
        {
            var    diag = new Mock <IDiagnostics>();
            string code = @"
                fun kju (): Unit {
                    4 * 6 = 5;
                }
                ";

            Assert.ThrowsException <ParseTreeToAstConverterException>(
                () => KjuCompilerUtils.GenerateAst(code, diag.Object));
            MockDiagnostics.Verify(diag, KjuParseTreeToAstConverter.AssignmentLhsErrorDiagnosticsType);
        }
Ejemplo n.º 16
0
        public void TestWrongDeclaration()
        {
            var v = new Variable(new Range(new StringLocation(0), new StringLocation(1)), "f");

            var x = new VariableDeclaration(
                new Range(new StringLocation(0), new StringLocation(1)),
                IntType.Instance,
                "f",
                null);

            var fc = new FunctionCall(
                new Range(new StringLocation(0), new StringLocation(1)),
                "f",
                new List <Expression>());

            var instructionBlock = new InstructionBlock(
                new Range(new StringLocation(0), new StringLocation(1)),
                new List <Expression> {
                v, x, fc
            });
            var f = new FunctionDeclaration(
                new Range(new StringLocation(0), new StringLocation(1)),
                "f",
                UnitType.Instance,
                new List <VariableDeclaration>(),
                instructionBlock,
                false);

            var diagnosticsMock = new Moq.Mock <IDiagnostics>();
            var diagnostics     = diagnosticsMock.Object;

            var functions = new List <FunctionDeclaration> {
                f
            };
            var root = new Program(
                new Range(new StringLocation(0), new StringLocation(1)),
                new List <StructDeclaration>(),
                functions);

            Assert.ThrowsException <NameResolverException>(() => this.nameResolver.Run(root, diagnostics));
            MockDiagnostics.Verify(
                diagnosticsMock,
                NameResolver.IdentifierNotFoundDiagnostic);
        }
Ejemplo n.º 17
0
        public void ExecutableExamples(IKjuExample example)
        {
            var options = new Program.Options
            {
                GenExe = true
            };
            var exeName = $"{TestsDirectory}/{example.SimpleName}";
            var query   = new CompilationQuery(example.Program, exeName);
            var diag    = new Mock <IDiagnostics>();

            Program.GenerateArtifacts(options, Compiler, query, diag.Object);
            var process = new System.Diagnostics.Process
            {
                StartInfo =
                {
                    FileName               = exeName,
                    Arguments              = string.Empty,
                    UseShellExecute        = false,
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true,
                    WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden,
                    CreateNoWindow         = true
                }
            };

            process.Start();
            using (var writer = process.StandardInput)
            {
                writer.Write(example.Input);
            }

            if (!process.WaitForExit(example.Timeout))
            {
                process.Kill();
                if (example.Ends)
                {
                    Assert.Fail($"Process has not ended before timeout ({example.Timeout}).");
                }
            }
            else
            {
                var exitCode = process.ExitCode;
                if (!example.Ends)
                {
                    Assert.Fail($"Should not end but ended with exit code {exitCode}.");
                }

                Assert.AreEqual(
                    example.ExpectedExitCode,
                    exitCode,
                    $"Process returned with wrong exit code.");
            }

            var processOutput = process.StandardOutput.ReadToEnd();

            var outputCheckResult = example.OutputChecker.CheckOutput(processOutput);

            outputCheckResult.Notes.ForEach(Console.WriteLine);
            if (outputCheckResult is OutputCheckResult.Wrong)
            {
                Assert.Fail("Output is wrong.");
            }

            MockDiagnostics.Verify(diag, example.ExpectedMagicStrings.ToArray());
        }