File: turing.rb

package info (click to toggle)
ruby-tins 1.32.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,248 kB
  • sloc: ruby: 6,659; makefile: 3
file content (312 lines) | stat: -rwxr-xr-x 7,228 bytes parent folder | download
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#!/usr/bin/env ruby

require 'term/ansicolor'
require 'tins'

module Turing
  class Tape
    def initialize(*initials)
      @left = []
      @head = 'B'
      @right = []
      c = 0
      first = true
      for initial in initials
        if first
          c += 1
          first = false
        else
          @left.push 'B'
          c += 1
        end
        for s in initial.split(//)
          @left.push s
          c += 1
        end
      end
      c.times { left }
    end

    def read
      @head
    end

    def write(symbol)
      @head = symbol
      self
    end

    def left
      @right.push @head
      @head = @left.pop || 'B'
      self
    end

    def right
      @left.push @head
      @head = @right.pop || 'B'
      self
    end

    def clear
      @left.clear
      @right.clear
      @head = 'B'
      self
    end

    def to_s
      "#{@left.join}#{Term::ANSIColor.red(@head)}#{@right.join.reverse}"
    end

    alias inspect to_s
  end

  module States
    class State
      attr_accessor :tape
    end

    class Cond < State
      def initialize(opts = {})
        @if, @then, @else = opts.values_at :if, :then, :else
      end

      def execute
        tape.read == @if ? @then : @else
      end

      def to_s
        "if #@if then #@then else #@else"
      end

      def to_graphviz(stateno, tapeno = nil)
        %{#{stateno} [ shape=diamond label="#{tapeno && "#{tapeno}: "}#@if" ];
          #{stateno} -> #@then [ taillabel="+" ];
          #{stateno} -> #@else [ taillabel="-" ];
          #{stateno} -> #{stateno} [ label="#{stateno}" weight=4.0 color=transparent ];}
      end
    end

    class Left < State
      def initialize(opts = {})
        @goto = opts[:goto]
      end

      def execute
        tape.left
        @goto
      end

      def to_s
        "left, goto #@goto"
      end

      def to_graphviz(stateno, tapeno = nil)
        %{#{stateno} [ shape=rect label="#{tapeno && "#{tapeno}: "}L" ];
          #{stateno} -> #@goto;
          #{stateno} -> #{stateno} [ label="#{stateno}" weight=4.0 color=transparent ];}
      end
    end

    class Right < State
      def initialize(opts = {})
        @goto = opts[:goto]
      end

      def execute
        tape.right
        @goto
      end

      def to_s
        "right, goto #@goto"
      end

      def to_graphviz(stateno, tapeno = nil)
        %{#{stateno} [ shape=rect label="#{tapeno && "#{tapeno}: "}R" ];
          #{stateno} -> #@goto;
          #{stateno} -> #{stateno} [ label="#{stateno}" weight=4.0 color=transparent ];}
      end
    end

    class Write < State
      def initialize(opts = {})
        @symbol, @goto = opts.values_at :symbol, :goto
      end

      def execute
        tape.write @symbol
        @goto
      end

      def to_s
        "write #@symbol, goto #@goto"
      end

      def to_graphviz(stateno, tapeno = nil)
        %{#{stateno} [ shape=rect label="#{tapeno && "#{tapeno}: "}#@symbol" ];
          #{stateno} -> #@goto;
          #{stateno} -> #{stateno} [ label="#{stateno}" weight=4.0 color=transparent ];}
      end
    end

    class Halt < State
      def initialize(opts = {})
      end

      def execute
        -1
      end

      def to_s
        'halt'
      end

      def to_graphviz(stateno, tapeno = nil)
        %{#{stateno} [ shape=rect label="HALT" ];
          #{stateno} -> #{stateno} [ label="#{stateno}" weight=4.0 color=transparent ];}
      end
    end
  end

  class BaseMachine
    def initialize(program = nil, &block)
      @states = []
      if program
        block_given? and raise "use either program source string or a block"
        interpret program
      else
        instance_eval(&block)
      end
    end

    def step(*tapes)
      @stepping = true
      run(*tapes)
    end
  end

  class SingleTapeMachine < BaseMachine
    include Tins::Deflect
    include Tins::Interpreter

    def initialize(program = nil)
      deflector = Deflector.new do |number, id, name, *args|
        opts = Hash === args.last ? args.pop : {}
        state = States.const_get(name.to_s.capitalize).new(opts)
        @states[number] = state
      end
      deflect_start(Integer, :method_missing, deflector)
      super
    ensure
      deflect_stop(Integer, :method_missing) if deflect?(Integer, :method_missing)
    end

    def run(*tape)
      @tape = Tape.new(*tape)
      @states.each { |s| s and s.tape = @tape }
      goto_state = -1
      @states.any? { |s| goto_state += 1; s }
      begin
        printf "%3u: %s", goto_state, @tape
        @stepping ? STDIN.gets : puts
        goto_state = @states[goto_state].execute
      end until goto_state < 0
    end

    def to_s
      result = ''
      @states.each_with_index do |state, i|
        result << "%3u. %s\n" % [ i, state ]
      end
      result
    end

    def to_graphviz
      result = "digraph {\n"
      start_edge = false
      @states.each_with_index do |state, stateno|
        state or next
        unless start_edge
          result << "start [ fontcolor=transparent color=transparent ];"
          result << "start -> #{stateno};"
          start_edge = true
        end
        result << state.to_graphviz(stateno) << "\n"
      end
      result << "}\n"
    end
  end

  class MultiTapeMachine < BaseMachine
    include Tins::Deflect
    include Tins::Interpreter

    def initialize(program = nil)
      deflector = Deflector.new do |number, id, name, *args|
        opts = Hash === args.last ? args.pop : {}
        tape, = *args
        state = States.const_get(name.to_s.capitalize).new(opts)
        @states[number] = [ tape, state ]
      end
      deflect_start(Integer, :method_missing, deflector)
      super
    ensure
      deflect_stop(Integer, :method_missing) if deflect?(Integer, :method_missing)
    end

    def run(*tapes)
      tapes.unshift ''
      @tapes = tapes.map { |tape| Tape.new(tape) }
      goto_state = -1
      @states.any? { |s| goto_state += 1; s }
      begin
        printf "%3u: %s", goto_state, @tapes * ' '
        @stepping ? STDIN.gets : puts
        tape, state = @states[goto_state]
        state.tape = tape ? @tapes[tape] : nil
        goto_state = state.execute
      end until goto_state < 0
    end

    def to_s
      result = ''
      @states.each_with_index do |(tape, state), i|
        result << "%3u. %1u: %s\n" % [ i, tape, state ]
      end
      result
    end

    def to_graphviz
      result = "digraph {\n"
      start_edge = false
      @states.each_with_index do |(tapeno,state), stateno|
        state or next
        unless start_edge
          result << "start [ fontcolor=transparent color=transparent ];"
          result << "start -> #{stateno};"
          start_edge = true
        end
        result << state.to_graphviz(stateno, tapeno) << "\n"
      end
      result << "}\n"
    end
  end
end

if $0 == __FILE__ and ARGV.any?
  include Turing
  filename, *tapes = ARGV
  machine_type =
    case ext = File.extname(filename)
    when '.stm'
      SingleTapeMachine
    when '.mtm'
      MultiTapeMachine
    else
      raise "unknown turing machine suffix: #{ext}, use .stm or .mtm"
    end
  tm = machine_type.new(File.read(filename))
  $DEBUG ? tm.step(*tapes) : tm.run(*tapes)
end