Code
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void WriteLine(string message)
{
Console.WriteLine(message);
}
static void WriteError(string message)
{
WriteLine(message);
Process.GetCurrentProcess().Kill();
}
//Получаем C# код по коду brainfuck
static string translateBrainFuck(string bf_code)
{
string res = "";
//Функции, которые должны быть описаны в шаблоне :
// changeElement(value) - изменение значения элемента в текущей ячейке на value
// memoryIndex - индекс текущей ячейки памяти
// outputElement - вывод символа, соответствующего текущему значению ячейки памяти
// inputElement - запись в ячейку кода введённого символа
//Заменыв формате
//<brainfuck> <C#> <cycle>
//где :
// cycle == 0 если конструкция не задаёт цикла
// cycle == 1 если конструкция открывает цикл
// cycle == 2 если конструкция закрывает цикл
object[] replaces ={new string[]{"+","changeElement(+1);","0"},
new string[]{"-","changeElement(-1);","0"},
new string[]{">","memoryIndex++;","0"},
new string[]{"<","memoryIndex--;","0"},
new string[]{".","outputElement();","0"},
new string[]{",","inputElement();","0"},
new string[]{"[","while(getElement()!=0){","1"},
new string[]{"]","}","2"}};
//Количество отступов
int tabcount = 3;
foreach (char chr in bf_code)
{
int i = 0;
string[] obj;
//Поиск соответствующей символу замены
int replaceNum = -1;
while(replaceNum==-1){
obj=(string[])replaces[i];
if(obj[0]==chr.ToString()){
replaceNum=i;
}
i++;
if (i > replaces.Length)
{
WriteError("Fatal error: illegal character '" + chr.ToString() + "'");
}
}
obj=(string[])replaces[replaceNum];
string c_sharp = obj[1];
string cycle = obj[2];
string tabs = "";
int tabchange = 0;
//Изменение отступа
if (cycle == "1") {
//Для начала цикла отступ поменяем уже после дописывания в код цикла
tabchange = 1;
}
else
if (cycle == "2") {
tabcount--;
}
//Формируем табуляции
for (i = 1; i <= tabcount; i++)
{tabs += "\t";}
tabcount += tabchange;
res += tabs + c_sharp+"\n";
}
return res;
}
static void Main(string[] args)
{
try
{
if (args[0].IndexOf("help") != -1)
{
WriteError("this is translator from brainfuck to c#.\n Written by Pozharckey Alexander in 2011.\n May use Mono for compilation created C# code");
}
}
catch { }
//Загрузка настроек из конфига
StreamReader config = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "brainfuck.conf");
string pattern = config.ReadLine().Replace("THIS.",AppDomain.CurrentDomain.BaseDirectory);
string monoPath = config.ReadLine();
config.Close();
string code = "";
string bf_code="";
string line = "";
string brainfuckFile = "";
string outFName = "";
try
{
brainfuckFile = args[0];
outFName = brainfuckFile.Replace(".bf", ".cs");
Environment.CurrentDirectory = Path.GetDirectoryName(brainfuckFile);
}
catch
{
WriteError("Error in parameters.\n Use :\n bf.exe \"brainfuckFileName\" -c(if need to compile file)");
}
StreamReader file;
try
{
WriteLine("Reading BRAINFUCK code file : '" + brainfuckFile + "'");
file = new StreamReader(brainfuckFile);
bf_code = file.ReadToEnd();
file.Close();
}
catch
{
WriteError("Error while reading : '" + brainfuckFile + "'");
}
WriteLine("File '" + brainfuckFile + "' readed succesfully");
try
{
WriteLine("Reading template : '"+pattern+"'");
file = new StreamReader(pattern);
while ((line = file.ReadLine()) != null)
{
if (line.IndexOf("//body") == -1)
{
code += line + "\n";
}
else
{
code += translateBrainFuck(bf_code) + "\n";
}
}
file.Close();
}
catch
{
WriteError("Error while reading template '" + pattern + "'");
}
WriteLine("File '" + pattern + "' readed sucessfully");
try
{
WriteLine("Writing C# result to : '" + outFName + "'");
StreamWriter outFile = new StreamWriter(outFName);
outFile.Write(code);
outFile.Close();
}
catch
{
WriteError("Error while writing C# result to : '" + outFName + "'");
}
WriteLine("C# result succesfully writed to : '" + outFName + "'");
try
{
if (args[1] == "-c")
{
Process monoProc = new Process();
monoProc.StartInfo.UseShellExecute = false;
monoProc.StartInfo.FileName = monoPath;
monoProc.StartInfo.Arguments = "\"" + outFName + "\"";
monoProc.StartInfo.WorkingDirectory = Path.GetDirectoryName(outFName);
monoProc.StartInfo.RedirectStandardOutput = true;
monoProc.StartInfo.RedirectStandardError = true;
monoProc.Start();
monoProc.WaitForExit();
WriteLine("Mono standart output : \n"+monoProc.StandardOutput.ReadToEnd());
WriteLine("Mono error output : \n" + monoProc.StandardError.ReadToEnd());
}
}
catch { }
}
}
}
[/spiler]
Код шаблона
[spoiler]
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace CnsoleApp
{
class Program
{
static ArrayList memory = new ArrayList();
static int memoryIndex = 0;
static void changeElement(int value)
{
try
{
memory[memoryIndex] = (int)memory[memoryIndex] + value;
}
catch
{
memory.Add(value);
}
}
static int getElement()
{
try
{
return (int)memory[memoryIndex];
}
catch
{
return 0;
}
}
static void inputElement()
{
ConsoleKeyInfo k = Console.ReadKey();
int code=(int)(Encoding.ASCII.GetBytes(new char[]{k.KeyChar})[0]);
try
{
memory[memoryIndex]=code;
}
catch
{
memory.Add(code);
}
}
static void outputElement()
{
int iEL=(int)memory[memoryIndex];
byte[] el = { (byte)iEL };
char chr = Encoding.ASCII.GetChars(el)[0];
Console.Write(chr);
}
static void Main(string[] args)
{
int memoryIndex=0;
//body
Console.Write("\n");
}
}
}