Changeset 9 for trunk/UBrainFuck.pas


Ignore:
Timestamp:
Feb 9, 2012, 4:10:10 PM (13 years ago)
Author:
chronos
Message:
  • Added: Easy compiler to Delphi.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/UBrainFuck.pas

    r8 r9  
    66
    77uses
    8   Classes, SysUtils, Dialogs, Forms;
     8  Classes, SysUtils, Dialogs, Forms, StrUtils;
    99
    1010type
    1111  TBrainFuckInterpretter = class;
    1212
    13   { TBrainFuck }
    14 
    15   TBrainFuck = class
    16     Source: TStringList;
    17     Output: TStringList;
     13  TCompilerTarget = (ctDelphi);
     14  { TBrainFuckCompiler }
     15
     16  TBrainFuckCompiler = class
     17  private
     18    Indent: Integer;
     19    procedure AddLine(Text: string);
     20  public
     21    Source: string;
     22    Output: string;
     23    Target: TCompilerTarget;
    1824    procedure Compile;
    1925  end;
     
    218224end;
    219225
    220 { TBrainFuck }
    221 
    222 procedure TBrainFuck.Compile;
    223 begin
    224 
     226{ TBrainFuckCompiler }
     227
     228procedure TBrainFuckCompiler.AddLine(Text: string);
     229begin
     230  Output := Output + DupeString(' ', Indent) + Text + LineEnding;
     231end;
     232
     233procedure TBrainFuckCompiler.Compile;
     234var
     235  I: Integer;
     236begin
     237  Indent := 0;
     238  Output := '';
     239
     240  AddLine('program Brainfuck;');
     241  AddLine('');
     242  AddLine('{$APPTYPE CONSOLE}');
     243  AddLine('');
     244  AddLine('uses');
     245  AddLine('  Classes;');
     246  AddLine('  ');
     247  AddLine('var');
     248  AddLine('  Memory: array[0..30000] of Char;');
     249  AddLine('  Position: Integer;');
     250  AddLine('begin');
     251  for I := 1 to Length(Source) do begin
     252    case Source[I] of
     253      '>': AddLine('Inc(Position);');
     254      '<': AddLine('Dec(Position);');
     255      '+': AddLine('Memory[Position] := Memory[Position] + 1');
     256      '-': AddLine('Memory[Position] := Memory[Position] - 1');
     257      '.': AddLine('Write(Memory[Position]);');
     258      ',': AddLine('Read(Memory[Position]);');
     259      '[': begin
     260        AddLine('while Memory[Position] <> 0 do begin');
     261        Inc(Indent, 2);
     262      end;
     263      ']': begin
     264        Dec(Indent, 2);
     265        AddLine('end;');
     266      end;
     267    end;
     268  end;
     269  AddLine('end.');
    225270end;
    226271
Note: See TracChangeset for help on using the changeset viewer.