/
ast.rb
686 lines (575 loc) · 15.6 KB
/
ast.rb
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
# Copyright (c) 2010 The Mirah project authors. All Rights Reserved.
# All contributing project authors may be found in the NOTICE file.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'delegate'
require 'mirah/transform'
require 'mirah/ast/scope'
module Mirah
module AST
class << self
attr_accessor :verbose
end
# The top of the AST class hierarchy, this represents an abstract AST node.
# It provides accessors for _children_, an array of all child nodes,
# _parent_, a reference to this node's parent (nil if none), and _newline_,
# whether this node represents a new line.
class Node
include Java::DubyLangCompiler.Node
include Enumerable
attr_accessor :children
attr_accessor :parent
attr_accessor :position
attr_accessor :newline
attr_accessor :inferred_type
def self.child(name)
@children ||= []
index = @children.size
class_eval <<-EOF
def #{name}
@children[#{index}]
end
def #{name}=(node)
@children[#{index}] = _set_parent(node)
end
EOF
@children << name
end
def self.child_name(i)
@children[i] if @children
end
def child_nodes
java.util.ArrayList.new(@children)
end
def initialize(parent, position, children = [])
JRuby.reference(self.class).setRubyClassAllocator(JRuby.reference(self.class).reified_class)
unless parent.nil? || Mirah::AST::Node === parent
raise "Mirah::AST::Node.new parent #{parent.class} must be nil or === Mirah::AST::Node."
end
@parent = parent
@newline = false
@inferred_type = nil
@resolved = false
@position = position
if block_given?
@children ||= []
@children = yield(self) || []
else
@children = children
end
end
def _dump(depth)
to_skip = %w(@parent @newline @inferred_type @resolved @proxy @scope @class_scope @static_scope @typer)
vars = {}
instance_variables.each do |name|
next if to_skip.include?(name)
vars[name] = instance_variable_get(name)
begin
Mirah::AST::Unquote.extract_values do
Marshal.dump(vars[name]) if AST.verbose
end
rescue
puts "#{self}: Failed to marshal #{name}"
puts inspect
puts $!, $@
raise $!
end
end
Marshal.dump(vars)
end
def self._load(vars)
node = self.allocate
Marshal.load(vars).each do |name, value|
node.instance_variable_set(name, value)
end
node.children.each do |child|
node._set_parent(child)
end
node.validate_children
node
end
def validate_children
validate_name if respond_to?(:validate_name)
children.each_with_index do |child, i|
validate_child(child, i)
end
end
def validate_child(child, i)
name = self.class.child_name(i)
validator = :"validate_#{name}"
if name && respond_to?(validator)
send validator
else
if UnquotedValue === child
self[i] = child.node
end
end
end
def line_number
if @position
@position.start_line + 1
else
0
end
end
def log(message)
puts "* [AST] [#{simple_name}] " + message if AST.verbose
end
def inspect_children(indent = 0)
indent_str = ' ' * indent
str = ''
children.each_with_index do |child, i|
extra_indent = 0
if child
name = self.class.child_name(i)
if Mirah::AST.verbose && name
str << "\n#{indent_str} #{name}:"
extra_indent = 1
end
if ::Array === child
child.each {|ary_child|
if Mirah::AST.verbose && Node === ary_child && ary_child.parent != self
str << "\n#{indent_str} (wrong parent)"
end
str << "\n#{ary_child.inspect(indent + extra_indent + 1)}"
}
elsif ::Hash === child || ::String === child
str << "\n#{indent_str} #{child.inspect}"
else
if Mirah::AST.verbose && Node === child && child.parent != self
str << "\n#{indent_str} (wrong parent)"
end
begin
str << "\n#{child.inspect(indent + extra_indent + 1)}"
rescue ArgumentError => ex
str << "\n#{indent_str} #{child.inspect}"
end
end
end
end
str
end
def inspect(indent = 0)
indent_str = ' ' * indent
indent_str << to_s << inspect_children(indent)
end
def simple_name
self.class.name.split("::")[-1]
end
def to_s; simple_name; end
def string_value
raise Mirah::SyntaxError.new("Can't use #{self.class} as string literal")
end
def [](index) children[index] end
def []=(index, node)
node.parent = self
@children[index] = node
end
def each(&b) children.each(&b) end
def <<(node)
@children << _set_parent(node)
self
end
def insert(index, node)
node.parent = self
@children.insert(index, node)
end
def empty?
@children.empty?
end
def resolved!(typer=nil)
log "#{to_s} resolved!"
@resolved = true
end
def resolved?; @resolved end
def resolve_if(typer)
unless resolved?
@inferred_type = yield
@inferred_type ? resolved!(typer) : typer.defer(self)
end
@inferred_type
end
def self.===(other)
super || (other.kind_of?(NodeProxy) && (self === other.__getobj__))
end
def _set_parent(node)
case node
when Node
node.parent = self
when ::Array
node.each {|x| x.parent = self if x}
end
node
end
def initialize_copy(other)
# bug: node is deferred, but it's parent isn't
# parent gets duped
# duped parent is inferred so it's children aren't
# original node gets inferred, but not the duplicate child
@inferred_type = @resolved = nil
@parent = nil
@children = []
other.children.each do |child|
case child
when ::Array
self << child.map {|x| x.dup}
when nil
self << nil
else
self << child.dup
end
end
end
def inferred_type!
unless @inferred_type
raise Mirah::InternalCompilerError.new(
"Internal Error: #{self.class} never inferred", self)
end
inferred_type
end
end
class ErrorNode < Node
def initialize(parent, error)
super(parent, error.position)
@error = error
@inferred_type = TypeReference::ErrorType
@resolved = true
end
def infer(typer, expression)
end
end
module Named
attr_reader :name
def name=(name)
if Node === name
name.parent = self
end
@name = name
end
def to_s
"#{super}(#{name})"
end
def string_value
name
end
def validate_name
if UnquotedValue === @name
@name = @name.name
end
end
end
module Typed
attr_accessor :type
end
module Valued
include Typed
attr_accessor :value
end
module Literal
include Typed
attr_accessor :literal
def to_s
"#{super}(#{literal.inspect})"
end
def string_value
literal.to_s
end
end
module Annotated
attr_accessor :annotations
def annotation(name)
name = name.to_s
annotations.find {|a| a.name == name}
end
end
module Binding
def binding_type(duby=nil)
static_scope.binding_type(defining_class, duby)
end
def binding_type=(type)
static_scope.binding_type = type
end
def has_binding?
static_scope.has_binding?
end
end
class Colon2 < Node; end
class Constant < Node
include Named
include Scoped
attr_accessor :array
def initialize(parent, position, name)
self.name = name
super(parent, position, [])
end
def infer(typer, expression)
@inferred_type ||= begin
# TODO lookup constant, inline if we're supposed to.
typer.type_reference(scope, name, @array, true)
end
end
def type_reference(typer)
typer.type_reference(scope, @name, @array)
end
end
class Self < Node
include Scoped
def infer(typer, expression)
@inferred_type ||= scope.static_scope.self_type
end
end
class Annotation < Node
attr_reader :values
attr_accessor :runtime
alias runtime? runtime
child :name_node
def initialize(parent, position, name=nil, &block)
super(parent, position, &block)
if name
@name = if name.respond_to?(:class_name)
name.class_name
else
name.name
end
end
@values = {}
end
def name
@name
end
def type
BiteScript::ASM::Type.getObjectType(@name.tr('.', '/'))
end
def []=(name, value)
@values[name] = value
end
def [](name)
@values[name]
end
def infer(typer, expression)
@inferred ||= begin
@name = name_node.type_reference(typer).name if name_node
@values.each do |name, value|
if Node === value
@values[name] = annotation_value(value, typer)
end
end
true
end
end
def annotation_value(node, typer)
case node
when String
java.lang.String.new(node.literal)
when Array
node.children.map {|node| annotation_value(node, typer)}
else
# TODO Support other types
ref = value.type_refence(typer)
desc = BiteScript::Signature.class_id(ref)
BiteScript::ASM::Type.getType(desc)
end
end
end
class NodeProxy < DelegateClass(Node)
include Java::DubyLangCompiler::Node
def __inline__(node)
node.parent = parent
__setobj__(node)
end
def dup
value = __getobj__.dup
if value.respond_to?(:proxy=)
new = super
new.__setobj__(value)
new.proxy = new
new
else
value
end
end
def _dump(depth)
Marshal.dump(__getobj__)
end
def self._load(str)
value = Marshal.load(str)
if value.respond_to?(:proxy=)
proxy = NodeProxy.new(value)
proxy.proxy = proxy
else
value
end
end
end
class TypeReference < Node
include Named
attr_accessor :array
alias array? array
attr_accessor :meta
alias meta? meta
def initialize(name, array = false, meta = false, position=nil)
super(nil, position)
self.name = name
@array = array
@meta = meta
end
def type_reference(typer)
typer.type_reference(nil, name, array, meta)
end
def to_s
"Type(#{name}#{array? ? ' array' : ''}#{meta? ? ' meta' : ''})"
end
def full_name
"#{name}#{array ? '[]' : ''}"
end
def ==(other)
to_s == other.to_s
end
def eql?(other)
self == other
end
def hash
to_s.hash
end
def is_parent(other)
# default behavior now is to disallow any polymorphic types
self == other
end
def compatible?(other)
# default behavior is only exact match right now
self == other ||
error? || other.error? ||
unreachable? || other.unreachable?
end
def iterable?
array?
end
def component_type
AST.type(nil, name) if array?
end
def basic_type
if array? || meta?
TypeReference.new(name, false, false)
else
self
end
end
def narrow(other)
# only exact match allowed for now, so narrowing is a noop
if error? || unreachable?
other
else
self
end
end
def unmeta
TypeReference.new(name, array, false)
end
def meta
TypeReference.new(name, array, true)
end
def void?
name == :void
end
def error?
name == :error
end
def null?
name == :null
end
def unreachable?
name == :unreachable
end
def block?
name == :block
end
def primitive?
true
end
def _dump(depth)
Marshal.dump([name, array?, meta?])
end
def self._load(str)
AST::Type(*Marshal.load(str))
end
NoType = TypeReference.new(:notype)
NullType = TypeReference.new(:null)
ErrorType = TypeReference.new(:error)
UnreachableType = TypeReference.new(:unreachable)
BlockType = TypeReference.new(:block)
end
class TypeDefinition < TypeReference
attr_accessor :superclass, :interfaces
def initialize(name, superclass, interfaces)
super(name, false)
@superclass = superclass
@interfaces = interfaces
end
end
def self.type_factory
Thread.current[:ast_type_factory]
end
def self.type_factory=(factory)
Thread.current[:ast_type_factory] = factory
end
# Shortcut method to construct type references
def self.type(scope, typesym, array = false, meta = false)
factory = type_factory
if factory
factory.type(scope, typesym, array, meta)
else
TypeReference.new(typesym, array, meta)
end
end
def self.no_type
factory = type_factory
if factory
factory.no_type
else
TypeReference::NoType
end
end
def self.error_type
TypeReference::ErrorType
end
def self.unreachable_type
TypeReference::UnreachableType
end
def self.block_type
TypeReference::BlockType
end
def self.fixnum(parent, position, literal)
Fixnum.new(parent, position, literal)
end
def self.float(parent, position, literal)
Float.new(parent, position, literal)
end
def self.defmacro(name, &block)
@macros ||= {}
raise "Conflicting macros for #{name}" if @macros[name]
@macros[name] = block
end
def self.macro(name)
@macros[name]
end
end
end
require 'mirah/ast/local'
require 'mirah/ast/call'
require 'mirah/ast/flow'
require 'mirah/ast/literal'
require 'mirah/ast/method'
require 'mirah/ast/class'
require 'mirah/ast/structure'
require 'mirah/ast/type'
require 'mirah/ast/intrinsics'