1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
#!/usr/bin/ruby -w
# L00P2rb converter in Ruby, written by cypher
output = File.open(ARGV[1], "w+") if ARGV[1]
output ||= $stdout
translate = {
?- => '$c[p] -= 1',
?+ => '$c[p] += 1',
?< => 'p -= 1; p.wrap!',
?> => 'p += 1; p.wrap!',
?, => '$c[p] = $stdin.read(1)',
?. => 'print $c[p].chr',
?; => '$c[p] = $stdin.readline.to_i',
?: => 'print $c[p]',
?& => 'break',
?* => '$c[p] *= 2',
?0 => '$c[p] = 0',
?_ => '$c[p] = -$c[p]',
?@ => '$c[p] = $c[(p + $c[p.wrap!]).wrap]',
?# => 'p = (p + $c[p.wrap!]).wrap',
?$ => '$c[(p + $c[p.wrap!]).wrap] = $c[p]',
?( => 'if $c[p] != 0',
?| => 'else',
?) => 'end',
?[ => 'if $c[p] == 0',
?] => 'end',
?S => '$c[p] = $c[p]>0 ? 1 : ( $c[p] < 0 ? -1 : 0 )'
}
source = (File.open(ARGV[0]) rescue nil || $stdin).read.gsub( /[^\-\+\<\>\*0\_\@\#\$\&\(\)\|\[\]\,\.\;\:S]/, '' )
raise "Error: Unbalanced '(' or ')'" if source.count('(') != source.count(')')
raise "Error: Unbalanced '[' or ']'" if source.count('[') != source.count(']')
output << <<RBEGIN
#!/usr/bin/ruby -w
$c = Array.new(8192) { Integer(0) }
p = 0
class Fixnum
def wrap!
self = (-self / $c.size + 1) * $c.size + self if self < 0
end
def wrap
self.dup.wrap!
end
end
while true
RBEGIN
indent = 1
source.each_byte do |chr|
indent -= 1 if chr==?) or chr==?] or chr==?|
output << "#{' ' * indent}#{translate[chr]}\n"
indent += 1 if chr==?( or chr==?[ or chr==?|
end
output << <<REND
end
REND
output.flush; output.close |