Example #1
0
        public void DefDefinesFunctionAndDoesntEatColon()
        {
            var tokens = new List <IToken>
            {
                new Token("FN", TokenClass.Statement, TokenType.Fn),
                new Token("NAME"),
                new Token("(", TokenClass.Seperator, TokenType.OpenBracket),
                new Token("A"),
                new Token(")", TokenClass.Seperator, TokenType.CloseBracket),
                new Token("=", TokenClass.Seperator, TokenType.Equal),
                new Token("A"),
                new Token("*", TokenClass.Seperator, TokenType.Multiply),
                new Token("A"),
                new Token(":", TokenClass.Seperator, TokenType.Colon)
            };

            _runEnvironment      = new RunEnvironment();
            _variableRepository  = new VariableRepository();
            _expressionEvaluator = new ExpressionEvaluator(_variableRepository, _runEnvironment);
            var programLine = new ProgramLine(10, tokens);

            _runEnvironment.CurrentLine = programLine;

            var sut = new Def(_runEnvironment, _expressionEvaluator);

            sut.Execute();

            Assert.AreEqual(TokenType.Colon, _runEnvironment.CurrentLine.NextToken().Seperator);
            var definition = _runEnvironment.DefinedFunctions["NAME"];

            Assert.AreEqual("NAME", definition.FunctionName);
            Assert.AreEqual("A", definition.VariableName);
            Assert.AreEqual(6, definition.LineToken);
            Assert.AreEqual(programLine, definition.Line);
        }
Example #2
0
        public void DefDefinesFunctionThrowsOnBadLineNumber()
        {
            var tokens = new List <IToken>
            {
                new Token("FN", TokenClass.Statement, TokenType.Fn),
                new Token("NAME"),
                new Token("(", TokenClass.Seperator, TokenType.OpenBracket),
                new Token("A"),
                new Token(")", TokenClass.Seperator, TokenType.CloseBracket),
                new Token("=", TokenClass.Seperator, TokenType.Equal),
                new Token("A"),
                new Token("*", TokenClass.Seperator, TokenType.Multiply),
                new Token("A"),
                new Token(":", TokenClass.Seperator, TokenType.Colon)
            };

            _runEnvironment      = new RunEnvironment();
            _variableRepository  = new VariableRepository();
            _expressionEvaluator = new ExpressionEvaluator(_variableRepository, _runEnvironment);
            var programLine = new ProgramLine(null, tokens);

            _runEnvironment.CurrentLine = programLine;

            var sut = new Def(_runEnvironment, _expressionEvaluator);

            Test.Throws <IllegalDirectException>(sut.Execute);
        }
Example #3
0
        public void DefDefinesFunctionThrowsOnBadToken(int insertRemAt, string nextToken, string message)
        {
            var tokens = new List <IToken>
            {
                new Token("FN", TokenClass.Statement, TokenType.Fn),
                new Token("NAME"),
                new Token("(", TokenClass.Seperator, TokenType.OpenBracket),
                new Token("A"),
                new Token(")", TokenClass.Seperator, TokenType.CloseBracket),
                new Token("=", TokenClass.Seperator, TokenType.Equal),
                new Token("A"),
                new Token("*", TokenClass.Seperator, TokenType.Multiply),
                new Token("A"),
                new Token(":", TokenClass.Seperator, TokenType.Colon)
            };

            tokens.Insert(insertRemAt, new Token("bang", TokenClass.Remark));

            _runEnvironment      = new RunEnvironment();
            _variableRepository  = new VariableRepository();
            _expressionEvaluator = new ExpressionEvaluator(_variableRepository, _runEnvironment);
            var programLine = new ProgramLine(10, tokens);

            _runEnvironment.CurrentLine = programLine;
            var sut = new Def(_runEnvironment, _expressionEvaluator);

            Test.Throws <SyntaxErrorException>(sut.Execute);
            Assert.AreEqual(nextToken, _runEnvironment.CurrentLine.NextToken().Text);
        }
Example #4
0
        public void ExecutingProgramThrowsSyntaxErrorCallsErrorHandlingWhenSet()
        {
            SetupSut();
            var tokens = new List <IToken>
            {
                _mockPrintToken.Object,
                _mockColonToken.Object,
                _mockPrintToken.Object,
                _mockNotStatement.Object
            };

            var line10 = new ProgramLine(10, tokens);

            _runEnvironment.CurrentLine           = line10;
            _runEnvironment.OnErrorGotoLineNumber = 30;
            _runEnvironment.ProgramStack.Push(new StackEntry());
            _runEnvironment.ProgramStack.Push(new StackEntry());
            _runEnvironment.ProgramStack.Push(new StackEntry());
            _mockProgramRepository.Setup(mpr => mpr.GetNextLine(20)).Returns <ProgramLine>(null);
            _mockProgramRepository.Setup(mpr => mpr.GetLine(30))
            .Returns(new ProgramLine(30, new List <IToken> {
                _mockPrintToken.Object
            }));

            var result = _sut.ExecuteLine();

            Assert.AreEqual(10, _runEnvironment.LastErrorLine);
            Assert.AreEqual(2, _runEnvironment.LastErrorNumber);
            Assert.AreEqual(3, _runEnvironment.LastErrorStackCount);
            Assert.AreEqual(2, _runEnvironment.LastErrorToken);
        }
        public void InterpreterHandlesImmediateSyntaxError()
        {
            var runLine = new ProgramLine(null, new List <IToken> {
                new Token("A")
            });

            SetupSut();

            _mockTeletype.Input.Enqueue("RUN");
            _mockTeletype.Input.Enqueue("SYSTEM");

            _mockTokeniser.Setup(mt => mt.Tokenise("RUN")).Returns(runLine);

            var syntaxException = new ClassicBasic.Interpreter.Exceptions.SyntaxErrorException();

            _mockExecutor.SetupSequence(me => me.ExecuteLine())
            .Throws(syntaxException)
            .Returns(true);
            _mockRunEnvironment.Setup(mre => mre.CurrentLine).Returns(runLine);

            _sut.Execute();

            // Run
            CheckForPrompt();

            CheckForError("?" + syntaxException.ErrorMessage + " ERROR");

            // Prompt after STOP
            CheckForPrompt();

            // Nothing left
            Assert.AreEqual(0, _mockTeletype.Output.Count);
        }
Example #6
0
        /// <inheritdoc/>
        protected override void OnRender(DrawingContext drawingContext)
        {
            TextView textView   = this.TextView;
            Size     renderSize = this.RenderSize;

            if (textView != null && textView.VisualLinesValid && codeEditor.CurrentProgram != null)
            {
                var foreground = (Brush)GetValue(Control.ForegroundProperty);
                foreach (VisualLine line in textView.VisualLines)
                {
                    int lineNumber = line.FirstDocumentLine.LineNumber;
                    if (codeEditor.CurrentProgram.Lines.Count >= lineNumber)
                    {
                        ProgramLine prgLine = codeEditor.CurrentProgram.Lines[lineNumber - 1];
                        if (prgLine.Type == ProgramLineType.OpCodeInstruction ||
                            (prgLine.Type == ProgramLineType.AssemblerDirective && prgLine.DirectiveName.StartsWith("DEF")))
                        {
                            string hexAddress = prgLine.LineAddress.ToString("X4");

                            FormattedText text = CreateFormattedText(
                                hexAddress,
                                typeface, emSize, foreground
                                );
                            double y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
                            drawingContext.DrawText(text, new Point(renderSize.Width - text.Width, y - textView.VerticalOffset));
                        }
                    }
                }
            }
        }
        public void TokenPushedBackWhenAtStartOfLineThrowsException(bool throwsException)
        {
            ProgramLine programLine = new ProgramLine(30, _tokens);
            var         token       = throwsException ? new Token(")", TokenClass.Seperator, TokenType.CloseBracket) : programLine.NextToken();

            Test.Throws <InvalidOperationException>(() => programLine.PushToken(token), throwsException);
        }
Example #8
0
        public void ExecutingListAndHittingBreakStopsExecutionTimes()
        {
            SetupSut();
            var line10 = new ProgramLine(10, new List <IToken> {
                _mockListToken.Object
            });

            int counter = 0;

            _mockListCmd.Setup(mlc => mlc.Execute())
            .Returns(false)
            .Callback(() =>
            {
                counter++;
                if (counter > 5)
                {
                    _mockTeletype.RaiseCancelEvent();
                }
            });
            _runEnvironment.CurrentLine = line10;
            _mockProgramRepository.Setup(mpr => mpr.GetNextLine(20)).Returns <ProgramLine>(null);

            var result = _sut.ExecuteLine();

            Assert.IsFalse(result);
            _mockListCmd.Verify(mlc => mlc.Setup(), Times.Once);
            _mockListCmd.Verify(mlc => mlc.Execute(), Times.Exactly(6));
        }
Example #9
0
        public void ForNextLoopWithoutVariableTest()
        {
            SetupSut();
            var forCmd  = new For(_runEnvironment, _mockExpressionEvaluator.Object, _variableRepository);
            var nextCmd = new Next(_runEnvironment, _variableRepository);

            _mockExpressionEvaluator.SetupSequence(mee => mee.GetExpression())
            .Returns(new Accumulator(1.0))
            .Returns(new Accumulator(3.0));
            var line10 = new ProgramLine(10, new List <IToken> {
                new Token("A"), _equalToken, _toToken, _colonToken
            });
            var line20 = new ProgramLine(20, new List <IToken> {
                new Token("1")
            });

            _runEnvironment.CurrentLine = line10;

            forCmd.Execute();
            Assert.AreEqual(1.0, _variableRepository.GetOrCreateVariable("A", new short[] { }).GetValue().ValueAsDouble());
            Assert.AreEqual(1, _runEnvironment.ProgramStack.Count);
            var loopBackToken = _runEnvironment.CurrentLine.CurrentToken;

            // Execute next,
            line20.CurrentToken         = 0;
            _runEnvironment.CurrentLine = line20;
            nextCmd.Execute();

            // variable should be 2
            Assert.AreEqual(2.0, _variableRepository.GetOrCreateVariable("A", new short[] { }).GetValue().ValueAsDouble());

            // Should be back to just after for loop.
            Assert.AreEqual(10, _runEnvironment.CurrentLine.LineNumber.Value);
            Assert.AreEqual(loopBackToken, _runEnvironment.CurrentLine.CurrentToken);

            // Execute next, variable should be 3
            line20.CurrentToken         = 0;
            _runEnvironment.CurrentLine = line20;
            nextCmd.Execute();
            Assert.AreEqual(3.0, _variableRepository.GetOrCreateVariable("A", new short[] { }).GetValue().ValueAsDouble());
            Assert.AreEqual(10, _runEnvironment.CurrentLine.LineNumber.Value);
            Assert.AreEqual(loopBackToken, _runEnvironment.CurrentLine.CurrentToken);

            // Execute next
            line20.CurrentToken         = 0;
            _runEnvironment.CurrentLine = line20;
            nextCmd.Execute();

            // So we have exited the loop
            Assert.AreEqual(20, _runEnvironment.CurrentLine.LineNumber.Value);

            // Did we leave behind the token.
            var token = _runEnvironment.CurrentLine.NextToken();

            Assert.AreEqual("1", token.Text);

            // Variable should be 4.0
            Assert.AreEqual(4.0, _variableRepository.GetOrCreateVariable("A", new short[] { }).GetValue().ValueAsDouble());
            Assert.AreEqual(0, _runEnvironment.ProgramStack.Count);
        }
Example #10
0
        public void ReturnUsesReturnAddressAndForNextLoops()
        {
            var runEnvironment = new RunEnvironment();
            var sut            = new Return(runEnvironment);
            var line10         = new ProgramLine(10, new List <IToken> {
                new Token("1000")
            });
            var line1000 = new ProgramLine(1000, new List <IToken> {
            });

            line10.NextToken();
            runEnvironment.CurrentLine = line1000;
            runEnvironment.ProgramStack.Push(new StackEntry {
                Line = line10, LineToken = line10.CurrentToken
            });
            runEnvironment.ProgramStack.Push(new StackEntry {
                Line = line10, LineToken = line10.CurrentToken
            });
            runEnvironment.ProgramStack.Push(new StackEntry {
                VariableName = "A", Line = line10, LineToken = line10.CurrentToken
            });
            runEnvironment.ProgramStack.Push(new StackEntry {
                VariableName = "B", Line = line10, LineToken = line10.CurrentToken
            });
            sut.Execute();
            Assert.AreEqual(1, runEnvironment.ProgramStack.Count);
            Assert.AreEqual(line10, runEnvironment.CurrentLine);
        }
Example #11
0
        /// <summary>
        /// Called before execute, used to setup the line number range.
        /// </summary>
        public void Setup()
        {
            int?start = _runEnvironment.CurrentLine.GetLineNumber();
            int?end   = start;

            var token = _runEnvironment.CurrentLine.NextToken();

            if (token.Seperator == TokenType.Minus || token.Seperator == TokenType.Comma)
            {
                end = _runEnvironment.CurrentLine.GetLineNumber();
            }
            else
            {
                _runEnvironment.CurrentLine.PushToken(token);
            }

            _startLine = start ?? 0;
            _endLine   = end ?? ushort.MaxValue;

            _currentLine = _programRepository.GetFirstLine();
            while (_currentLine != null && _currentLine.LineNumber < _startLine)
            {
                _currentLine = _programRepository.GetNextLine(_currentLine.LineNumber.Value);
            }
        }
Example #12
0
        private string GetNextDataStatement()
        {
            if (_currentDataLine == null)
            {
                if (_faulted)
                {
                    throw new Exceptions.OutOfDataException();
                }

                RestoreToLineNumber(null);
            }

            while (_currentDataLine != null)
            {
                while (!_currentDataLine.EndOfLine)
                {
                    var token = _currentDataLine.NextToken();
                    if (token.TokenClass == TokenClass.Data)
                    {
                        return(token.Text);
                    }
                }

                _currentDataLine = _programRepository.GetNextLine(_currentDataLine.LineNumber.Value);
                _runEnvironment.DataErrorLine = _currentDataLine?.LineNumber;
            }

            _faulted = true;
            throw new Exceptions.OutOfDataException();
        }
Example #13
0
        public void ForNextLoopWithNoVariableAndIntermediateGosubThrowsErrorTest()
        {
            SetupSut();
            var forCmd  = new For(_runEnvironment, _mockExpressionEvaluator.Object, _variableRepository);
            var nextCmd = new Next(_runEnvironment, _variableRepository);

            _mockExpressionEvaluator.SetupSequence(mee => mee.GetExpression())
            .Returns(new Accumulator(1.0))
            .Returns(new Accumulator(4.0));
            var line10 = new ProgramLine(10, new List <IToken> {
                new Token("A"), _equalToken, _toToken, _colonToken
            });
            var line30 = new ProgramLine(30, new List <IToken> {
                new Token("2")
            });

            // Execute for
            _runEnvironment.CurrentLine = line10;
            forCmd.Execute();

            // Pretend we've done a gosub
            _runEnvironment.ProgramStack.Push(new StackEntry());
            line30.CurrentToken         = 0;
            _runEnvironment.CurrentLine = line30;
            Test.Throws <NextWithoutForException>(nextCmd.Execute);
        }
        public void InterpreterHandlesBreakBeingThrownByRead()
        {
            var runLine = new ProgramLine(null, new List <IToken> {
                new Token("A")
            });

            SetupSut();

            _mockTeletype.Input.Enqueue("BREAK");
            _mockTeletype.Input.Enqueue("SYSTEM");

            _mockTokeniser.Setup(mt => mt.Tokenise("RUN")).Returns(runLine);

            _mockTeletype.CancelEventHandler += MockTeletype_CancelEventHandler;

            _sut.Execute();

            // Run
            CheckForPrompt();

            // Prompt after STOP
            CheckForPrompt();

            // Nothing left
            Assert.AreEqual(0, _mockTeletype.Output.Count);
        }
        public void InterpreterAddsProgramLines()
        {
            var line10 = new ProgramLine(10, new List <IToken> {
                new Token("A")
            });
            var line20 = new ProgramLine(20, new List <IToken> {
                new Token("A")
            });

            SetupSut();

            _mockTeletype.Input.Enqueue("10 PRINT");
            _mockTeletype.Input.Enqueue("20 PRINT");
            _mockTeletype.Input.Enqueue("SYSTEM");

            _mockTokeniser.Setup(mt => mt.Tokenise("10 PRINT")).Returns(line10);
            _mockTokeniser.Setup(mt => mt.Tokenise("20 PRINT")).Returns(line20);

            _mockExecutor.SetupSequence(me => me.ExecuteLine())
            .Returns(true);

            _sut.Execute();

            _mockProgramRepository.Verify(s => s.SetProgramLine(line10), Times.Once);
            _mockProgramRepository.Verify(s => s.SetProgramLine(line20), Times.Once);
        }
Example #16
0
        private void CheckExpandMacro(String text, String[] expected, String message)
        {
            ProgramLine target = ProgramLine.Parse(text);
            IEnumerable <ProgramLine> result = target.ExpandMacro();

            CheckProgramLines(result, expected, message);
        }
Example #17
0
        private void SetupSut()
        {
            _mockExpressionEvaluator = new Mock <IExpressionEvaluator>();
            string fileContents =
                @"10 REM LINE 10
20 REM LINE 20
30 REM LINE 30";
            string missingLineContents =
                @"10 REM LINE 10
20 REM LINE 20
REM LINE 30";

            _mockFileSystem = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { @"c:\myfile.bas", new MockFileData(fileContents) },
                { @"c:\missing.bas", new MockFileData(missingLineContents) },
            });
            _mockProgramRepository = new Mock <IProgramRepository>();
            _mockTokeniser         = new Mock <ITokeniser>();
            _line10 = new ProgramLine(10, new List <IToken> {
            });
            _line20 = new ProgramLine(20, new List <IToken> {
            });
            _line30 = new ProgramLine(30, new List <IToken> {
            });
            _mockTokeniser.Setup(mt => mt.Tokenise("10 REM LINE 10")).Returns(_line10);
            _mockTokeniser.Setup(mt => mt.Tokenise("20 REM LINE 20")).Returns(_line20);
            _mockTokeniser.Setup(mt => mt.Tokenise("30 REM LINE 30")).Returns(_line30);
            _mockTokeniser.Setup(mt => mt.Tokenise("REM LINE 30")).Returns(new ProgramLine(null, new List <IToken> {
            }));
            _sut = new Load(_mockExpressionEvaluator.Object, _mockFileSystem, _mockProgramRepository.Object);
        }
Example #18
0
        private void CheckGenerateCode(ProgramLine target, Word[] expectedWords, String message)
        {
            RelocatableModule relModule = new RelocatableModule();

            target.GenerateCode(relModule);
            RelocatableModuleTest.CheckWords(relModule, expectedWords, message);
        }
        public int AddBreakpointOnProgramLine(ProgramInMemory programInMemory, int lineNumber)
        {
            ProgramLine programLine = programInMemory.Program.Lines[lineNumber - 1];
            InstructionAddressCondition instructionAddressCondition = new InstructionAddressCondition(programLine.LineAddress);
            int breakpointIndex = CPU.AddExitCondition(instructionAddressCondition);

            return(breakpointIndex);
        }
Example #20
0
 /// <summary>
 /// Implements moving the current data pointer to a new line number
 /// </summary>
 /// <param name="lineNumber">line number to move to, null moves to beginning of program.</param>
 public void RestoreToLineNumber(int?lineNumber)
 {
     _currentDataLine = lineNumber.HasValue
         ? _programRepository.GetLine(lineNumber.Value)
         : _programRepository.GetFirstLine();
     ReadInputParser.Clear();
     _faulted = false;
 }
        public void ProgramLineReturnsThreeTokens()
        {
            ProgramLine programLine = new ProgramLine(30, _tokens);

            Assert.AreEqual("ONE", programLine.NextToken().Text);
            Assert.AreEqual("TWO", programLine.NextToken().Text);
            Assert.AreEqual("THREE", programLine.NextToken().Text);
        }
        public void ProgramLineEndOfLineIsTrueOnceTokensRead()
        {
            ProgramLine programLine = new ProgramLine(30, _tokens);

            programLine.NextToken();
            programLine.NextToken();
            programLine.NextToken();
            Assert.IsTrue(programLine.EndOfLine);
        }
    void processProgram()
    {
        string[]    lines = this.program.Split('\n');
        ProgramLine lineObject;

        foreach (string line in lines)
        {
            lineObject = new ProgramLine(line);
            this.programLines.Add(lineObject, this.instructionSet);
        }
    }
        public void EvaluatorGetLine()
        {
            var tokens = new List <IToken>
            {
                new Token("2000")
            };
            ProgramLine programLine = new ProgramLine(30, tokens);
            var         result      = programLine.GetLineNumber();

            Assert.AreEqual(2000, result);
        }
Example #25
0
        public void ExecutingProgramThrowsSyntaxErrorIfNextTokenIsNotVariableOrStatement()
        {
            SetupSut();
            var line10 = new ProgramLine(10, new List <IToken> {
                _mockPrintToken.Object, _mockNotStatement.Object
            });

            _runEnvironment.CurrentLine = line10;
            _mockProgramRepository.Setup(mpr => mpr.GetNextLine(20)).Returns <ProgramLine>(null);
            var result = Test.Throws <SyntaxErrorException, bool>(_sut.ExecuteLine, true);
        }
        public void ProgramLineEndOfLineIsFalseIfLastTokenPushedBack()
        {
            ProgramLine programLine = new ProgramLine(30, _tokens);

            programLine.NextToken();
            programLine.NextToken();
            var lastToken = programLine.NextToken();

            Assert.IsTrue(programLine.EndOfLine);
            programLine.PushToken(lastToken);
            Assert.IsFalse(programLine.EndOfLine);
        }
        public void EvaluatorGetLineReturnsNullAndTokenIsNotEaten()
        {
            var tokens = new List <IToken>
            {
                new Token("DATA", TokenClass.Statement, TokenType.Data)
            };
            ProgramLine programLine = new ProgramLine(30, tokens);
            var         result      = programLine.GetLineNumber();

            Assert.AreEqual(null, result);
            Assert.AreEqual("DATA", programLine.NextToken().Text);
        }
        public void WrongTokenPushedBackThrowsException(bool throwsException)
        {
            ProgramLine programLine = new ProgramLine(30, _tokens);

            programLine.NextToken();
            var secondToken = programLine.NextToken();
            var thirdToken  = programLine.NextToken();

            var token = throwsException ? secondToken : thirdToken;

            Test.Throws <InvalidOperationException>(() => programLine.PushToken(token), throwsException);
        }
        public void EvaluatorGetLineThrowsExceptionOnBadLineNumber()
        {
            var tokens = new List <IToken>
            {
                new Token("20X00")
            };
            ProgramLine programLine = new ProgramLine(30, tokens);
            var         result      = programLine.GetLineNumber();

            Assert.IsNull(result);
            Assert.AreEqual("20X00", programLine.NextToken().Text);
        }
Example #30
0
        public void ListTestWithOptions(int?start, string token, int?end, string expectedLines)
        {
            var tokens      = new List <IToken>();
            var currentLine = new ProgramLine(null, tokens);

            SetupSut();
            _runEnvironment.CurrentLine = currentLine;
            if (start.HasValue)
            {
                tokens.Add(new Token(start.Value.ToString()));
            }

            if (token != null)
            {
                tokens.Add(new Token(
                               token,
                               TokenClass.Seperator,
                               token == "-" ? TokenType.Minus : TokenType.Comma));
            }

            if (end.HasValue)
            {
                tokens.Add(new Token(end.Value.ToString()));
            }

            _sut.Setup();
            int endlessLoop = 10;

            while (!_sut.Execute() && endlessLoop > 0)
            {
                endlessLoop--;
            }

            Assert.AreNotEqual(0, endlessLoop);
            if (expectedLines == null)
            {
                Assert.AreEqual(0, _teletype.Output.Count);
            }
            else
            {
                int cnt   = 0;
                var lines = expectedLines.Split(",");
                while (_teletype.Output.Count > 0)
                {
                    var output = _teletype.Output.Dequeue();
                    Assert.IsTrue(output.StartsWith(lines[cnt++]));
                    var crLf = _teletype.Output.Dequeue();
                    Assert.AreEqual(System.Environment.NewLine, crLf);
                }

                Assert.AreEqual(lines.Length, cnt);
            }
        }