Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for cell value-wrapping and IndexOutOfBounds on unmatching loop tokens #1

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 19 additions & 11 deletions BFLib/Brainfuck.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,29 @@ public static class Brainfuck
/// <summary>
/// Runs the provided Brainfuck code.
/// </summary>
/// <param name="code">The code to run.</param>
public static void Run(string code)
/// <param name="code">
/// The code to run.
/// </param>
/// <param name="stdin">
/// Optional. The input stream. Console is used if not specified.
/// </param>
/// <param name="stdout">
/// Optional. The ouput stream. Console is used if not specified.
/// </param>
public static void Run(string code, Stream stdin = null, Stream stdout = null)
{
Tape tape = new Tape();

char[] program = code.ToCharArray();
int brackets = 0;
int codePointer = 0;

Stream stdin = Console.OpenStandardInput();
Stream stdout = Console.OpenStandardOutput();
if (stdin == null)
stdin = Console.OpenStandardInput();
if (stdout == null)
stdout = Console.OpenStandardOutput();

while (codePointer < program.Length)
while (codePointer >= 0 && codePointer < program.Length)
{
switch (program[codePointer])
{
Expand All @@ -36,20 +46,19 @@ public static void Run(string code)
codePointer++;
break;
case '>':
tape.Right();
tape.MoveRight();
codePointer++;
break;
case '<':
tape.Left();
tape.MoveLeft();
codePointer++;
break;
case '[':
if (tape.Cell == 0)
{
brackets++;
while (brackets != 0)
while (brackets != 0 && ++codePointer < program.Length)
{
codePointer++;
if (program[codePointer] == '[')
brackets++;
else if (program[codePointer] == ']')
Expand All @@ -62,9 +71,8 @@ public static void Run(string code)
break;
case ']':
brackets++;
while (brackets != 0)
while (brackets != 0 && --codePointer >= 0)
{
codePointer--;
if (program[codePointer] == ']')
brackets++;
else if (program[codePointer] == '[')
Expand Down
81 changes: 60 additions & 21 deletions BFLib/Tape.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,43 +7,82 @@ namespace BrainTools
/// </summary>
internal class Tape
{
private List<int> tapeList;
private int index;
const int MIN_CELL_VALUE = 0, MAX_CELL_VALUE = 255;

private List<int> content;
internal int Pointer;



public Tape()
{
this.content = new List<int>();
content.Add(0);
this.Pointer = 0;
}



public int Cell
{
get
{
return this.tapeList[this.index];
return this.content[this.Pointer];
}
set
{
this.tapeList[this.index] = value;
}
}
/*
* If the assigned value is larger than the byte's size, keep deducting
* the max byte size, until the value is smaller. If deducted, finally
* reduce the value by one.
*/
bool mod = false;
while (value > MAX_CELL_VALUE)
{
value -= MAX_CELL_VALUE;
mod = true;
}

public void Right()
{
this.index++;
if (this.index == this.tapeList.Count)
this.tapeList.Add(0);
if (mod)
value--;

/*
* If the assigned value is smaller than the zero, keep adding the max
* byte size, until the value is greater. If added, finally add the value
* by one.
*/
mod = false;
while (value < -MAX_CELL_VALUE)
{
value += MAX_CELL_VALUE;
mod = true;
}

if (mod)
value++;

if (value < MIN_CELL_VALUE)
value = (MAX_CELL_VALUE + 1) + value;

this.content[this.Pointer] = value;
}
}

public void Left()
public void MoveLeft()
{
this.index--;
if (this.index == -1)
this.Pointer--;
if (this.Pointer == -1)
{
this.tapeList.Insert(0, 0);
this.index++;
this.content.Insert(0, 0);
this.Pointer++;
}
}

public Tape()
public void MoveRight()
{
this.tapeList = new List<int>();
tapeList.Add(0);
this.index = 0;
this.Pointer++;
if (this.Pointer == this.content.Count)
this.content.Add(0);
}
}
}
}
89 changes: 89 additions & 0 deletions BFTests/BFTests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{8EBAAD50-1CB1-4A30-B464-AAF17DD04D90}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>BFTests</RootNamespace>
<AssemblyName>BFTests</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<Choose>
<When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
</ItemGroup>
</When>
<Otherwise>
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework" />
</ItemGroup>
</Otherwise>
</Choose>
<ItemGroup>
<Compile Include="BrainfuckTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BFLib\BFLib.csproj">
<Project>{9fbb13f0-f0ea-44e3-aae1-52b02d0766c6}</Project>
<Name>BFLib</Name>
</ProjectReference>
</ItemGroup>
<Choose>
<When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
</ItemGroup>
</When>
</Choose>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
61 changes: 61 additions & 0 deletions BFTests/BrainfuckTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using BrainTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Text;

namespace BFTests
{
[TestClass]
public class BrainfuckTests
{
private string RunMemoryBFTest(string bfCode, string inputCode = null)
{
if (inputCode == null)
inputCode = string.Empty;

using (MemoryStream msOut = new MemoryStream())
using (MemoryStream msIn = new MemoryStream(Encoding.ASCII.GetBytes(inputCode)))
{
Brainfuck.Run(bfCode, msIn, msOut);

return Encoding.ASCII.GetString(msOut.ToArray());
}
}

[TestMethod, Description("Validates the results of running a valid piece of BF code.")]
public void BasicBrainfuckTest()
{
Assert.AreEqual("Hello World!", RunMemoryBFTest(">+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.>>>++++++++[<++++>-]<.>>>++++++++++[<+++++++++>-]<---.<<<<.+++.------.--------.>>+."));
}

[TestMethod, Description("Validates the results of running a BF code with cell-wrapping.")]
public void CellWrappingTest()
{
Assert.AreEqual("H", RunMemoryBFTest("-[------->+<]>-."));
}

[TestMethod, Description("Validates that the loop-start operator jumps beyond the loop-end when cell value is zero.")]
public void LoopSkippingTest()
{
// The second loop should be skipped entirely since the cell value is zero.
Assert.AreEqual("F", RunMemoryBFTest("++++++++++[->+++++++<][>++++<]>."));
}

[TestMethod]
public void UnmatchedLoopTokenTest()
{
try
{
Brainfuck.Run("[++");
Brainfuck.Run("++]");
Brainfuck.Run("++[->++<]]");
}
catch (IndexOutOfRangeException)
{
// Test fails
Assert.Fail();
}
}
}
}
36 changes: 36 additions & 0 deletions BFTests/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BFTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BFTests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6d659f57-d7a0-40b1-8364-30a44d7cd940")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
18 changes: 16 additions & 2 deletions BrainTools.sln
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.40629.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BrainTools", "BrainTools\BrainTools.csproj", "{F532E232-B61C-4297-8ACB-FF237BA21D79}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BFLib", "BFLib\BFLib.csproj", "{9FBB13F0-F0EA-44E3-AAE1-52B02D0766C6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BFTests", "BFTests\BFTests.csproj", "{8EBAAD50-1CB1-4A30-B464-AAF17DD04D90}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -35,6 +39,16 @@ Global
{9FBB13F0-F0EA-44E3-AAE1-52B02D0766C6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{9FBB13F0-F0EA-44E3-AAE1-52B02D0766C6}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{9FBB13F0-F0EA-44E3-AAE1-52B02D0766C6}.Release|x86.ActiveCfg = Release|Any CPU
{8EBAAD50-1CB1-4A30-B464-AAF17DD04D90}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8EBAAD50-1CB1-4A30-B464-AAF17DD04D90}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8EBAAD50-1CB1-4A30-B464-AAF17DD04D90}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{8EBAAD50-1CB1-4A30-B464-AAF17DD04D90}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{8EBAAD50-1CB1-4A30-B464-AAF17DD04D90}.Debug|x86.ActiveCfg = Debug|Any CPU
{8EBAAD50-1CB1-4A30-B464-AAF17DD04D90}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8EBAAD50-1CB1-4A30-B464-AAF17DD04D90}.Release|Any CPU.Build.0 = Release|Any CPU
{8EBAAD50-1CB1-4A30-B464-AAF17DD04D90}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{8EBAAD50-1CB1-4A30-B464-AAF17DD04D90}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{8EBAAD50-1CB1-4A30-B464-AAF17DD04D90}.Release|x86.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down