~tim/scheme-vm

ref: e4df98a91597fb05fff508b8e9f71a104a9721d1 scheme-vm/compiler.rb -rw-r--r-- 9.4 KiB
e4df98a9Tim Morgan Add char and some list and string methods 6 years ago
                                                                                
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
require_relative 'vm'
require 'pp'

class Compiler
  def initialize(sexps = nil, arguments: {})
    @sexps = sexps
    @variables = {}
    @arguments = arguments
  end

  attr_reader :variables, :arguments

  def compile(sexps = @sexps, halt: true)
    instructions = compile_sexps(sexps)
    instructions + \
    (halt ? [VM::HALT] : [])
  end

  def pretty_format(instructions, grouped: false, ip: false)
    instructions = instructions.dup.flatten.compact
    count = 0
    [].tap do |pretty|
      while instructions.any?
        group = []
        group << count if ip
        if (instruction = instructions.shift)
          (name, arity) = VM::INSTRUCTIONS[instruction]
          group << "VM::#{name}"
          arity.times { group << instructions.shift }
          pretty << group
          count += group.size - 1
        else
          pretty << nil
        end
      end
    end.send(grouped ? :to_a : :flatten)
  end

  def pretty_print(instructions)
    pp pretty_format(instructions, grouped: true, ip: true)
  end

  private

  def compile_sexps(sexps, options = {})
    options[:locals] ||= {}
    options[:syntax] ||= {}
    sexps.each_with_index.flat_map do |sexp, index|
      compile_sexp(sexp, options.merge(use: index == sexps.size - 1))
    end.flatten.compact
  end

  def compile_sexp(sexp, options = { use: false, locals: {} })
    sexp = sexp.to_ruby if sexp.is_a?(VM::Pair)
    return compile_literal(sexp, options) unless sexp.is_a?(Array)
    return [] if sexp.empty?
    (name, *args) = sexp
    name = name.to_s if name.is_a?(VM::Atom)
    if options[:quote] || options[:quasiquote]
      if name =~ /unquote(\-splicing)?/ && options[:quasiquote] # FIXME move to a method
        expr = compile_sexp(args.first, options.merge(quasiquote: false))
        if name == 'unquote-splicing'
          fail "can only use unquote-splicing with a list" if expr.compact.last != VM::PUSH_LIST
          ['splice', expr.first]
        else
          expr
        end
      else
        list(sexp, options)
      end
    elsif name.is_a?(Array) || name.is_a?(VM::Pair)
      call(sexp, options)
    elsif respond_to?((underscored_name = name.gsub('->', '_to_').gsub(/([a-z])-/, '\1_')), :include_private)
      send(underscored_name, args, options)
    elsif (transformer = options[:syntax][name])
      macro = compile_sexp([transformer, ['quote', sexp]], options.merge(use: true)) + [VM::HALT]
      vm = VM.new(macro.flatten.compact)
      vm.execute
      begin
        val = vm.pop_val
      rescue VM::NoStackValue
        []
      else
        compile_sexp(val, options.merge(use: true)) + [pop_maybe(options)]
      end
    else
      call(sexp, options)
    end
  end

  # TODO rename this
  def compile_literal(literal, options = { use: false, locals: {} })
    literal = literal.to_s.strip
    case literal
    when /\A[a-z]/
      if options[:quote] || options[:quasiquote]
        [VM::PUSH_ATOM, literal]
      else
        [
          push_var(literal, options),
          pop_maybe(options)
        ]
      end
    when '#t'
      [VM::PUSH_TRUE, pop_maybe(options)]
    when '#f'
      [VM::PUSH_FALSE, pop_maybe(options)]
    when /\A#\\(.)/
      [VM::PUSH_CHAR, $1, pop_maybe(options)]
    when /\A"(.*)"\z/
      [VM::PUSH_STR, $1]
    when ''
      []
    else
      [
        VM::PUSH_NUM,
        literal,
        pop_maybe(options)
      ]
    end
  end

  def car((arg, *_rest), options)
    [
      compile_sexp(arg, options.merge(use: true)),
      VM::PUSH_CAR,
      pop_maybe(options)
    ]
  end

  def cdr((arg, *_rest), options)
    [
      compile_sexp(arg, options.merge(use: true)),
      VM::PUSH_CDR,
      pop_maybe(options)
    ]
  end

  def cons(args, options)
    fail 'cons expects exactly 2 arguments' if args.size != 2
    [
      args.map { |arg| compile_sexp(arg, options.merge(use: true)) },
      VM::PUSH_CONS,
      pop_maybe(options)
    ]
  end

  def append(args, options)
    [
      args.map { |arg| compile_sexp(arg, options.merge(use: true)) },
      VM::PUSH_NUM, args.size,
      VM::APPEND,
      pop_maybe(options)
    ]
  end

  def null?((arg, *_rest), options)
    [
      compile_sexp(arg, options.merge(use: true)),
      VM::CMP_NULL,
      pop_maybe(options)
    ]
  end

  def string_ref((string, index), options)
    [
      compile_sexp(string, options.merge(use: true)),
      compile_sexp(index, options.merge(use: true)),
      VM::STR_REF,
      pop_maybe(options)
    ]
  end

  def string_length((string, *_rest), options)
    [
      compile_sexp(string, options.merge(use: true)),
      VM::STR_LEN,
      pop_maybe(options)
    ]
  end

  def list_to_string((list, *_rest), options)
    [
      compile_sexp(list, options.merge(use: true)),
      VM::LIST_TO_STR,
      pop_maybe(options)
    ]
  end


  def quote((arg, *_rest), options)
    if arg.is_a?(Array)
      compile_sexp(arg, options.merge(quote: true))
    else
      compile_literal(arg, options.merge(quote: true))
    end
  end

  def quasiquote((arg, *_rest), options)
    if arg.is_a?(Array)
      compile_sexp(arg, options.merge(quasiquote: true))
    else
      compile_literal(arg, options.merge(quasiquote: true))
    end
  end

  def define((name, val), options)
    options[:locals][name] = true
    [
      compile_sexp(val, options.merge(use: true)),
      VM::SET_LOCAL, name
    ]
  end

  def lambda((args, *body), options)
    arg_locals = {}
    if args.is_a?(Array)
      if args.include?('.')
        (named, _dot, rest) = args.slice_when { |i, j| [i, j].include?('.') }.to_a
        arg_locals = (named + rest).each_with_object({}) { |arg, hash| hash[arg] = true }
        args = named.map { |name| push_arg(name) } + push_all_args(rest.first)
      else
        arg_locals = args.each_with_object({}) { |arg, hash| hash[arg] = true }
        args = args.map { |name| push_arg(name) }
      end
    else
      arg_locals = { args => true }
      args = push_all_args(args)
    end
    [
      VM::PUSH_FUNC,
      args,
      compile_sexps(body, locals: arg_locals),
      VM::RETURN,
      VM::ENDF,
      pop_maybe(options)
    ]
  end

  def call((lambda, *args), options)
    [
      args.map { |arg| compile_sexp(arg, options.merge(use: true)) },
      args.any? ? [VM::PUSH_NUM, args.size, VM::SET_ARGS] : nil,
      compile_sexp(lambda, options.merge(use: true)),
      VM::CALL
    ]
  end

  def apply((lambda, *args), options)
    fail 'apply expects at least 2 arguments' if args.empty?
    [
      args.map { |arg| compile_sexp(arg, options.merge(use: true)) },
      VM::PUSH_NUM, args.size,
      VM::SET_ARGS,
      compile_sexp(lambda, options.merge(use: true)),
      VM::APPLY
    ]
  end

  def list(args, options)
    members = args.flat_map do |arg|
      expr = compile_sexp(arg, options.merge(use: true))
      if expr.first == 'splice'
        expr.last
      else
        [expr]
      end
    end
    [
      members,
      VM::PUSH_NUM, members.size,
      VM::PUSH_LIST,
      pop_maybe(options)
    ]
  end

  def define_syntax((name, transformer), options)
    transformer.shift
    options[:syntax][name] = syntax_rules(transformer, options)
    []
  end

  # TODO: identifiers
  # TODO: bindings isolated from current scope
  def syntax_rules((_identifiers, *rules), options)
    last = []
    while (rule = rules.pop)
      (pattern, template) = rule
      names = pattern[1..-1]
      template = unquote_names_in_template(template, names)
      last = ['if', ['=', ['length', ['quote', pattern]], ['length', 'expr']],
               ['apply', ['lambda', names, ['quasiquote', template]], ['cdr', 'expr']],
               last]
    end
    ['lambda', ['expr'], last]
  end

  def unquote_names_in_template(template, names)
    return ['unquote', template] if names.include?(template)
    return template unless template.is_a?(Array)
    template.each_with_index do |part, index|
      template[index] = unquote_names_in_template(part, names)
    end
  end

  def if((condition, true_body, false_body), options)
    true_instr  = compile_sexp(true_body, options.merge(use: true)).flatten.compact
    false_instr = compile_sexp(false_body, options.merge(use: true)).flatten.compact
    [
      compile_sexp(condition, options.merge(use: true)),
      VM::JUMP_IF_FALSE, true_instr.size + 3,
      true_instr,
      VM::JUMP, false_instr.size + 1,
      false_instr,
      pop_maybe(options)
    ]
  end

  {
    '+'   => VM::ADD,
    '-'   => VM::SUB,
    '>'   => VM::CMP_GT,
    '>='  => VM::CMP_GTE,
    '<'   => VM::CMP_LT,
    '<='  => VM::CMP_LTE,
    '='   => VM::CMP_EQ_NUM,
    'eq?' => VM::CMP_EQ
  }.each do |name, instruction|
    define_method(name) do |args, options|
      compare(instruction, args, options)
    end
  end

  def include((arg), options)
    [
      compile_sexp(arg, options.merge(use: true)),
      VM::INT, VM::INT_INCLUDE
    ]
  end

  def compare(instruction, (arg1, arg2), options)
    [
      compile_sexp(arg1, options.merge(use: true)),
      compile_sexp(arg2, options.merge(use: true)),
      instruction,
      pop_maybe(options)
    ]
  end

  def print(args, options)
    [
      args.map { |arg| compile_sexp(arg, options.merge(use: true)) },
      VM::INT, VM::INT_PRINT_VAL
    ]
  end

  def push_var(name, options)
    [
      options[:locals][name] ? VM::PUSH_LOCAL : VM::PUSH_REMOTE,
      name
    ]
  end

  def push_arg(name, _options = {})
    [
      VM::PUSH_ARG,
      VM::SET_LOCAL, name
    ]
  end

  def push_all_args(name, _options = {})
    [
      VM::PUSH_ARGS,
      VM::SET_LOCAL, name
    ]
  end

  def pop_maybe(options)
    return VM::POP unless options[:use]
  end
end