-
Notifications
You must be signed in to change notification settings - Fork 914
/
ModuleNodes.java
1957 lines (1545 loc) · 82.4 KB
/
ModuleNodes.java
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2013, 2016 Oracle and/or its affiliates. All rights reserved. This
* code is released under a tri EPL/GPL/LGPL license. You can use it,
* redistribute it and/or modify it under the terms of the:
*
* Eclipse Public License version 1.0
* GNU General Public License version 2
* GNU Lesser General Public License version 2.1
*/
package org.jruby.truffle.core.module;
import com.oracle.truffle.api.CallTarget;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.RootCallTarget;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.CreateCast;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.NodeChildren;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.Frame;
import com.oracle.truffle.api.frame.FrameInstance;
import com.oracle.truffle.api.frame.FrameInstance.FrameAccess;
import com.oracle.truffle.api.frame.MaterializedFrame;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.IndirectCallNode;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.nodes.NodeUtil;
import com.oracle.truffle.api.object.DynamicObject;
import com.oracle.truffle.api.profiles.BranchProfile;
import com.oracle.truffle.api.profiles.ValueProfile;
import com.oracle.truffle.api.source.Source;
import com.oracle.truffle.api.source.SourceSection;
import org.jcodings.Encoding;
import org.jcodings.specific.UTF8Encoding;
import org.jruby.truffle.Layouts;
import org.jruby.truffle.RubyContext;
import org.jruby.truffle.builtins.CoreClass;
import org.jruby.truffle.builtins.CoreMethod;
import org.jruby.truffle.builtins.CoreMethodArrayArgumentsNode;
import org.jruby.truffle.builtins.CoreMethodNode;
import org.jruby.truffle.core.RaiseIfFrozenNode;
import org.jruby.truffle.core.cast.BooleanCastWithDefaultNodeGen;
import org.jruby.truffle.core.cast.NameToJavaStringNode;
import org.jruby.truffle.core.cast.NameToJavaStringNodeGen;
import org.jruby.truffle.core.cast.NameToSymbolOrStringNodeGen;
import org.jruby.truffle.core.cast.TaintResultNode;
import org.jruby.truffle.core.cast.ToPathNodeGen;
import org.jruby.truffle.core.cast.ToStrNode;
import org.jruby.truffle.core.cast.ToStrNodeGen;
import org.jruby.truffle.core.method.MethodFilter;
import org.jruby.truffle.core.rope.Rope;
import org.jruby.truffle.core.string.StringOperations;
import org.jruby.truffle.core.string.StringUtils;
import org.jruby.truffle.core.symbol.SymbolTable;
import org.jruby.truffle.language.LexicalScope;
import org.jruby.truffle.language.NotProvided;
import org.jruby.truffle.language.RubyConstant;
import org.jruby.truffle.language.RubyGuards;
import org.jruby.truffle.language.RubyNode;
import org.jruby.truffle.language.RubyRootNode;
import org.jruby.truffle.parser.TempSourceSection;
import org.jruby.truffle.language.SnippetNode;
import org.jruby.truffle.language.Visibility;
import org.jruby.truffle.language.arguments.MissingArgumentBehavior;
import org.jruby.truffle.language.arguments.ProfileArgumentNode;
import org.jruby.truffle.language.arguments.ReadPreArgumentNode;
import org.jruby.truffle.language.arguments.ReadSelfNode;
import org.jruby.truffle.language.arguments.RubyArguments;
import org.jruby.truffle.language.constants.GetConstantNode;
import org.jruby.truffle.language.constants.LookupConstantNode;
import org.jruby.truffle.language.control.RaiseException;
import org.jruby.truffle.language.dispatch.CallDispatchHeadNode;
import org.jruby.truffle.language.dispatch.DispatchHeadNodeFactory;
import org.jruby.truffle.language.loader.CodeLoader;
import org.jruby.truffle.language.loader.RequireNode;
import org.jruby.truffle.language.methods.AddMethodNode;
import org.jruby.truffle.language.methods.AddMethodNodeGen;
import org.jruby.truffle.language.methods.Arity;
import org.jruby.truffle.language.methods.CanBindMethodToModuleNode;
import org.jruby.truffle.language.methods.CanBindMethodToModuleNodeGen;
import org.jruby.truffle.language.methods.DeclarationContext;
import org.jruby.truffle.language.methods.GetCurrentVisibilityNode;
import org.jruby.truffle.language.methods.InternalMethod;
import org.jruby.truffle.language.methods.SharedMethodInfo;
import org.jruby.truffle.language.objects.IsANode;
import org.jruby.truffle.language.objects.IsANodeGen;
import org.jruby.truffle.language.objects.IsFrozenNode;
import org.jruby.truffle.language.objects.IsFrozenNodeGen;
import org.jruby.truffle.language.objects.ReadInstanceVariableNode;
import org.jruby.truffle.language.objects.SingletonClassNode;
import org.jruby.truffle.language.objects.SingletonClassNodeGen;
import org.jruby.truffle.language.objects.WriteInstanceVariableNode;
import org.jruby.truffle.language.yield.YieldNode;
import org.jruby.truffle.parser.ParserContext;
import org.jruby.truffle.parser.Translator;
import org.jruby.truffle.platform.UnsafeGroup;
import org.jruby.truffle.parser.Identifiers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@CoreClass("Module")
public abstract class ModuleNodes {
@TruffleBoundary
public static DynamicObject createModule(RubyContext context, DynamicObject selfClass, DynamicObject lexicalParent, String name, Node currentNode) {
final ModuleFields model = new ModuleFields(context, lexicalParent, name);
final DynamicObject module = Layouts.MODULE.createModule(Layouts.CLASS.getInstanceFactory(selfClass), model);
model.rubyModuleObject = module;
if (lexicalParent != null) {
Layouts.MODULE.getFields(module).getAdoptedByLexicalParent(context, lexicalParent, name, currentNode);
} else if (Layouts.MODULE.getFields(module).givenBaseName != null) { // bootstrap module
Layouts.MODULE.getFields(module).setFullName(Layouts.MODULE.getFields(module).givenBaseName);
}
return module;
}
@CoreMethod(names = "===", required = 1)
public abstract static class ContainsInstanceNode extends CoreMethodArrayArgumentsNode {
@Child private IsANode isANode;
public ContainsInstanceNode(RubyContext context, SourceSection sourceSection) {
super(context, sourceSection);
isANode = IsANodeGen.create(context, sourceSection, null, null);
}
@Specialization
public boolean containsInstance(DynamicObject module, Object instance) {
return isANode.executeIsA(instance, module);
}
}
@CoreMethod(names = "<", required = 1)
public abstract static class IsSubclassOfNode extends CoreMethodArrayArgumentsNode {
public abstract Object executeIsSubclassOf(VirtualFrame frame, DynamicObject self, DynamicObject other);
@TruffleBoundary
@Specialization(guards = "isRubyModule(other)")
public Object isSubclassOf(DynamicObject self, DynamicObject other) {
if (self == other) {
return false;
}
if (ModuleOperations.includesModule(self, other)) {
return true;
}
if (ModuleOperations.includesModule(other, self)) {
return false;
}
return nil();
}
@Specialization(guards = "!isRubyModule(other)")
public Object isSubclassOfOther(DynamicObject self, DynamicObject other) {
throw new RaiseException(coreExceptions().typeError("compared with non class/module", this));
}
}
@CoreMethod(names = "<=", required = 1)
public abstract static class IsSubclassOfOrEqualToNode extends CoreMethodArrayArgumentsNode {
public abstract Object executeIsSubclassOfOrEqualTo(DynamicObject self, DynamicObject other);
@TruffleBoundary
@Specialization(guards = "isRubyModule(other)")
public Object isSubclassOfOrEqualTo(DynamicObject self, DynamicObject other) {
if (self == other || ModuleOperations.includesModule(self, other)) {
return true;
}
if (ModuleOperations.includesModule(other, self)) {
return false;
}
return nil();
}
@Specialization(guards = "!isRubyModule(other)")
public Object isSubclassOfOrEqualToOther(DynamicObject self, DynamicObject other) {
throw new RaiseException(coreExceptions().typeError("compared with non class/module", this));
}
}
@CoreMethod(names = ">", required = 1)
public abstract static class IsSuperclassOfNode extends CoreMethodArrayArgumentsNode {
public abstract Object executeIsSuperclassOf(VirtualFrame frame, DynamicObject self, DynamicObject other);
@TruffleBoundary
@Specialization(guards = "isRubyModule(other)")
public Object isSuperclassOf(DynamicObject self, DynamicObject other) {
if (self == other) {
return false;
}
if (ModuleOperations.includesModule(other, self)) {
return true;
}
if (ModuleOperations.includesModule(self, other)) {
return false;
}
return nil();
}
@Specialization(guards = "!isRubyModule(other)")
public Object isSuperclassOfOther(DynamicObject self, DynamicObject other) {
throw new RaiseException(coreExceptions().typeError("compared with non class/module", this));
}
}
@CoreMethod(names = ">=", required = 1)
public abstract static class IsSuperclassOfOrEqualToNode extends CoreMethodArrayArgumentsNode {
public abstract Object executeIsSuperclassOfOrEqualTo(VirtualFrame frame, DynamicObject self, DynamicObject other);
@TruffleBoundary
@Specialization(guards = "isRubyModule(other)")
public Object isSuperclassOfOrEqualTo(DynamicObject self, DynamicObject other) {
if (self == other || ModuleOperations.includesModule(other, self)) {
return true;
}
if (ModuleOperations.includesModule(self, other)) {
return false;
}
return nil();
}
@Specialization(guards = "!isRubyModule(other)")
public Object isSuperclassOfOrEqualToOther(DynamicObject self, DynamicObject other) {
throw new RaiseException(coreExceptions().typeError("compared with non class/module", this));
}
}
@CoreMethod(names = "<=>", required = 1)
public abstract static class CompareNode extends CoreMethodArrayArgumentsNode {
@Child private IsSubclassOfOrEqualToNode subclassNode;
private Object isSubclass(DynamicObject self, DynamicObject other) {
if (subclassNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
subclassNode = insert(ModuleNodesFactory.IsSubclassOfOrEqualToNodeFactory.create(null));
}
return subclassNode.executeIsSubclassOfOrEqualTo(self, other);
}
@Specialization(guards = "isRubyModule(other)")
public Object compare(DynamicObject self, DynamicObject other) {
if (self == other) {
return 0;
}
final Object isSubclass = isSubclass(self, other);
if (isSubclass == nil()) {
return nil();
} else {
return (boolean) isSubclass ? -1 : 1;
}
}
@Specialization(guards = "!isRubyModule(other)")
public Object compareOther(DynamicObject self, DynamicObject other) {
return nil();
}
}
@CoreMethod(names = "alias_method", required = 2, raiseIfFrozenSelf = true, visibility = Visibility.PRIVATE)
@NodeChildren({
@NodeChild(type = RubyNode.class, value = "module"),
@NodeChild(type = RubyNode.class, value = "newName"),
@NodeChild(type = RubyNode.class, value = "oldName")
})
public abstract static class AliasMethodNode extends CoreMethodNode {
@CreateCast("newName")
public RubyNode coercetNewNameToString(RubyNode newName) {
return NameToJavaStringNodeGen.create(newName);
}
@CreateCast("oldName")
public RubyNode coerceOldNameToString(RubyNode oldName) {
return NameToJavaStringNodeGen.create(oldName);
}
@Specialization
public DynamicObject aliasMethod(DynamicObject module, String newName, String oldName) {
Layouts.MODULE.getFields(module).alias(getContext(), this, newName, oldName);
return module;
}
}
@CoreMethod(names = "ancestors")
public abstract static class AncestorsNode extends CoreMethodArrayArgumentsNode {
@TruffleBoundary
@Specialization
public DynamicObject ancestors(DynamicObject self) {
final List<DynamicObject> ancestors = new ArrayList<>();
for (DynamicObject module : Layouts.MODULE.getFields(self).ancestors()) {
ancestors.add(module);
}
Object[] objects = ancestors.toArray(new Object[ancestors.size()]);
return createArray(objects, objects.length);
}
}
@CoreMethod(names = "append_features", required = 1, visibility = Visibility.PRIVATE)
public abstract static class AppendFeaturesNode extends CoreMethodArrayArgumentsNode {
@Child TaintResultNode taintResultNode;
public AppendFeaturesNode(RubyContext context, SourceSection sourceSection) {
super(context, sourceSection);
taintResultNode = new TaintResultNode(context, sourceSection);
}
@Specialization(guards = "isRubyModule(target)")
public DynamicObject appendFeatures(DynamicObject features, DynamicObject target,
@Cached("create()") BranchProfile errorProfile) {
if (RubyGuards.isRubyClass(features)) {
errorProfile.enter();
throw new RaiseException(coreExceptions().typeError("append_features must be called only on modules", this));
}
Layouts.MODULE.getFields(target).include(getContext(), this, features);
taintResultNode.maybeTaint(features, target);
return nil();
}
}
@NodeChildren({ @NodeChild("module"), @NodeChild("name") })
public abstract static class GenerateAccessorNode extends RubyNode {
final boolean isGetter;
@Child NameToJavaStringNode nameToJavaStringNode;
public GenerateAccessorNode(RubyContext context, SourceSection sourceSection, boolean isGetter) {
super(context, sourceSection);
this.isGetter = isGetter;
this.nameToJavaStringNode = NameToJavaStringNode.create();
}
public abstract DynamicObject executeGenerateAccessor(VirtualFrame frame, DynamicObject module, Object name);
@Specialization
public DynamicObject generateAccessor(VirtualFrame frame, DynamicObject module, Object nameObject) {
final String name = nameToJavaStringNode.executeToJavaString(frame, nameObject);
createAccesor(module, name);
return nil();
}
@TruffleBoundary
private void createAccesor(DynamicObject module, String name) {
final FrameInstance callerFrame = getContext().getCallStack().getCallerFrameIgnoringSend();
final SourceSection sourceSection = callerFrame.getCallNode().getEncapsulatingSourceSection();
final TempSourceSection tempSourceSection = new TempSourceSection(sourceSection);
final Visibility visibility = DeclarationContext.findVisibility(callerFrame.getFrame(FrameAccess.READ_ONLY, true));
final Arity arity = isGetter ? Arity.NO_ARGUMENTS : Arity.ONE_REQUIRED;
final String ivar = "@" + name;
final String accessorName = isGetter ? name : name + "=";
final RubyNode checkArity = Translator.createCheckArityNode(getContext(), sourceSection.getSource(), tempSourceSection, arity);
final LexicalScope lexicalScope = new LexicalScope(getContext().getRootLexicalScope(), module);
final SharedMethodInfo sharedMethodInfo = new SharedMethodInfo(
sourceSection,
lexicalScope,
arity,
module,
accessorName,
"attr_" + (isGetter ? "reader" : "writer"),
null,
false,
false,
false);
final RubyNode self = new ProfileArgumentNode(new ReadSelfNode());
final RubyNode accessInstanceVariable;
if (isGetter) {
accessInstanceVariable = new ReadInstanceVariableNode(getContext(), sourceSection, ivar, self);
} else {
RubyNode readArgument = new ProfileArgumentNode(new ReadPreArgumentNode(0, MissingArgumentBehavior.RUNTIME_ERROR));
accessInstanceVariable = new WriteInstanceVariableNode(getContext(), sourceSection, ivar, self, readArgument);
}
final RubyNode sequence = Translator.sequence(getContext(), sourceSection.getSource(), tempSourceSection, Arrays.asList(checkArity, accessInstanceVariable));
final RubyRootNode rootNode = new RubyRootNode(getContext(), sourceSection, null, sharedMethodInfo, sequence, false);
final CallTarget callTarget = Truffle.getRuntime().createCallTarget(rootNode);
final InternalMethod method = new InternalMethod(getContext(), sharedMethodInfo, lexicalScope, accessorName, module, visibility, callTarget);
Layouts.MODULE.getFields(module).addMethod(getContext(), this, method);
}
}
@CoreMethod(names = "attr", rest = true, visibility = Visibility.PRIVATE)
public abstract static class AttrNode extends CoreMethodArrayArgumentsNode {
@Child GenerateAccessorNode generateGetterNode;
@Child GenerateAccessorNode generateSetterNode;
public AttrNode(RubyContext context, SourceSection sourceSection) {
super(context, sourceSection);
this.generateGetterNode = ModuleNodesFactory.GenerateAccessorNodeGen.create(context, sourceSection, true, null, null);
this.generateSetterNode = ModuleNodesFactory.GenerateAccessorNodeGen.create(context, sourceSection, false, null, null);
}
@Specialization
public DynamicObject attr(VirtualFrame frame, DynamicObject module, Object[] names) {
final boolean setter;
if (names.length == 2 && names[1] instanceof Boolean) {
setter = (boolean) names[1];
names = new Object[] { names[0] };
} else {
setter = false;
}
for (Object name : names) {
generateGetterNode.executeGenerateAccessor(frame, module, name);
if (setter) {
generateSetterNode.executeGenerateAccessor(frame, module, name);
}
}
return nil();
}
}
@CoreMethod(names = "attr_accessor", rest = true, visibility = Visibility.PRIVATE)
public abstract static class AttrAccessorNode extends CoreMethodArrayArgumentsNode {
@Child GenerateAccessorNode generateGetterNode;
@Child GenerateAccessorNode generateSetterNode;
public AttrAccessorNode(RubyContext context, SourceSection sourceSection) {
super(context, sourceSection);
this.generateGetterNode = ModuleNodesFactory.GenerateAccessorNodeGen.create(context, sourceSection, true, null, null);
this.generateSetterNode = ModuleNodesFactory.GenerateAccessorNodeGen.create(context, sourceSection, false, null, null);
}
@Specialization
public DynamicObject attrAccessor(VirtualFrame frame, DynamicObject module, Object[] names) {
for (Object name : names) {
generateGetterNode.executeGenerateAccessor(frame, module, name);
generateSetterNode.executeGenerateAccessor(frame, module, name);
}
return nil();
}
}
@CoreMethod(names = "attr_reader", rest = true, visibility = Visibility.PRIVATE)
public abstract static class AttrReaderNode extends CoreMethodArrayArgumentsNode {
@Child GenerateAccessorNode generateGetterNode;
public AttrReaderNode(RubyContext context, SourceSection sourceSection) {
super(context, sourceSection);
this.generateGetterNode = ModuleNodesFactory.GenerateAccessorNodeGen.create(context, sourceSection, true, null, null);
}
@Specialization
public DynamicObject attrReader(VirtualFrame frame, DynamicObject module, Object[] names) {
for (Object name : names) {
generateGetterNode.executeGenerateAccessor(frame, module, name);
}
return nil();
}
}
@CoreMethod(names = "attr_writer", rest = true, visibility = Visibility.PRIVATE)
public abstract static class AttrWriterNode extends CoreMethodArrayArgumentsNode {
@Child GenerateAccessorNode generateSetterNode;
public AttrWriterNode(RubyContext context, SourceSection sourceSection) {
super(context, sourceSection);
this.generateSetterNode = ModuleNodesFactory.GenerateAccessorNodeGen.create(context, sourceSection, false, null, null);
}
@Specialization
public DynamicObject attrWriter(VirtualFrame frame, DynamicObject module, Object[] names) {
for (Object name : names) {
generateSetterNode.executeGenerateAccessor(frame, module, name);
}
return nil();
}
}
@CoreMethod(names = "autoload", required = 2, unsafe = UnsafeGroup.LOAD)
@NodeChildren({
@NodeChild(type = RubyNode.class, value = "module"),
@NodeChild(type = RubyNode.class, value = "name"),
@NodeChild(type = RubyNode.class, value = "filename")
})
public abstract static class AutoloadNode extends CoreMethodNode {
public AutoloadNode(RubyContext context, SourceSection sourceSection) {
super(context, sourceSection);
}
@CreateCast("name") public RubyNode coerceNameToString(RubyNode name) {
return NameToJavaStringNodeGen.create(name);
}
@CreateCast("filename") public RubyNode coerceFilenameToPath(RubyNode filename) {
return ToPathNodeGen.create(null, null, filename);
}
@TruffleBoundary
@Specialization(guards = "isRubyString(filename)")
public DynamicObject autoload(DynamicObject module, String name, DynamicObject filename) {
if (!Identifiers.isValidConstantName19(name)) {
throw new RaiseException(coreExceptions().nameError(StringUtils.format("autoload must be constant name: %s", name), module, name, this));
}
if (StringOperations.rope(filename).isEmpty()) {
throw new RaiseException(coreExceptions().argumentError("empty file name", this));
}
if (Layouts.MODULE.getFields(module).getConstant(name) != null) {
return nil();
}
Layouts.MODULE.getFields(module).setAutoloadConstant(getContext(), this, name, filename);
return nil();
}
}
@CoreMethod(names = "autoload?", required = 1)
public abstract static class AutoloadQueryNode extends CoreMethodArrayArgumentsNode {
@Specialization(guards = "isRubySymbol(name)")
public Object autoloadQuerySymbol(DynamicObject module, DynamicObject name) {
return autoloadQuery(module, Layouts.SYMBOL.getString(name));
}
@Specialization(guards = "isRubyString(name)")
public Object autoloadQueryString(DynamicObject module, DynamicObject name) {
return autoloadQuery(module, name.toString());
}
private Object autoloadQuery(DynamicObject module, String name) {
final RubyConstant constant = ModuleOperations.lookupConstant(getContext(), module, name);
if ((constant == null) || ! constant.isAutoload()) {
return nil();
}
return constant.getValue();
}
}
@CoreMethod(names = { "class_eval", "module_eval" }, optional = 3, lowerFixnum = 3, needsBlock = true)
public abstract static class ClassEvalNode extends CoreMethodArrayArgumentsNode {
@Child private YieldNode yield;
@Child private ToStrNode toStrNode;
public ClassEvalNode(RubyContext context, SourceSection sourceSection) {
super(context, sourceSection);
yield = new YieldNode(context, DeclarationContext.CLASS_EVAL);
}
protected DynamicObject toStr(VirtualFrame frame, Object object) {
if (toStrNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
toStrNode = insert(ToStrNodeGen.create(getContext(), null, null));
}
return toStrNode.executeToStr(frame, object);
}
@Specialization(guards = "isRubyString(code)")
public Object classEval(VirtualFrame frame, DynamicObject module, DynamicObject code, NotProvided file, NotProvided line, NotProvided block, @Cached("create()") IndirectCallNode callNode) {
return classEvalSource(frame, module, code, "(eval)", callNode);
}
@Specialization(guards = {"isRubyString(code)", "isRubyString(file)"})
public Object classEval(VirtualFrame frame, DynamicObject module, DynamicObject code, DynamicObject file, NotProvided line, NotProvided block, @Cached("create()") IndirectCallNode callNode) {
return classEvalSource(frame, module, code, file.toString(), callNode);
}
@Specialization(guards = {"isRubyString(code)", "isRubyString(file)"})
public Object classEval(VirtualFrame frame, DynamicObject module, DynamicObject code, DynamicObject file, int line, NotProvided block, @Cached("create()") IndirectCallNode callNode) {
final CodeLoader.DeferredCall deferredCall = classEvalSource(module, code, file.toString(), line);
return deferredCall.call(frame, callNode);
}
@Specialization(guards = "wasProvided(code)")
public Object classEval(VirtualFrame frame, DynamicObject module, Object code, NotProvided file, NotProvided line, NotProvided block, @Cached("create()") IndirectCallNode callNode) {
return classEvalSource(frame, module, toStr(frame, code), file.toString(), callNode);
}
@Specialization(guards = {"isRubyString(code)", "wasProvided(file)"})
public Object classEval(VirtualFrame frame, DynamicObject module, DynamicObject code, Object file, NotProvided line, NotProvided block, @Cached("create()") IndirectCallNode callNode) {
return classEvalSource(frame, module, code, toStr(frame, file).toString(), callNode);
}
private Object classEvalSource(VirtualFrame frame, DynamicObject module, DynamicObject code, String file, @Cached("create()") IndirectCallNode callNode) {
final CodeLoader.DeferredCall deferredCall = classEvalSource(module, code, file, 1);
return deferredCall.call(frame, callNode);
}
@TruffleBoundary
private CodeLoader.DeferredCall classEvalSource(DynamicObject module, DynamicObject rubySource, String file, int line) {
assert RubyGuards.isRubyString(rubySource);
final Rope code = StringOperations.rope(rubySource);
final MaterializedFrame callerFrame = getContext().getCallStack().getCallerFrameIgnoringSend()
.getFrame(FrameInstance.FrameAccess.MATERIALIZE, true).materialize();
Encoding encoding = Layouts.STRING.getRope(rubySource).getEncoding();
// TODO (pitr 15-Oct-2015): fix this ugly hack, required for AS, copy-paste
final String s = new String(new char[Math.max(line - 1, 0)]);
final String space = StringUtils.replace(s, "\0", "\n");
Source source = getContext().getSourceLoader().loadFragment(space + code, file);
final RubyRootNode rootNode = getContext().getCodeLoader().parse(source, encoding, ParserContext.MODULE, callerFrame, true, this);
return getContext().getCodeLoader().prepareExecute(ParserContext.MODULE, DeclarationContext.CLASS_EVAL, rootNode, callerFrame, module);
}
@Specialization
public Object classEval(VirtualFrame frame, DynamicObject self, NotProvided code, NotProvided file, NotProvided line, DynamicObject block) {
return yield.dispatchWithModifiedSelf(frame, block, self, self);
}
@Specialization
public Object classEval(DynamicObject self, NotProvided code, NotProvided file, NotProvided line, NotProvided block) {
throw new RaiseException(coreExceptions().argumentError(0, 1, 2, this));
}
@Specialization(guards = "wasProvided(code)")
public Object classEval(DynamicObject self, Object code, NotProvided file, NotProvided line, DynamicObject block) {
throw new RaiseException(coreExceptions().argumentError(1, 0, this));
}
}
@CoreMethod(names = { "class_exec", "module_exec" }, rest = true, needsBlock = true)
public abstract static class ClassExecNode extends CoreMethodArrayArgumentsNode {
@Child private YieldNode yield;
public ClassExecNode(RubyContext context, SourceSection sourceSection) {
super(context, sourceSection);
yield = new YieldNode(context, DeclarationContext.CLASS_EVAL);
}
public abstract Object executeClassExec(VirtualFrame frame, DynamicObject self, Object[] args, Object block);
@Specialization
public Object classExec(VirtualFrame frame, DynamicObject self, Object[] args, DynamicObject block) {
return yield.dispatchWithModifiedSelf(frame, block, self, args);
}
@Specialization
public Object classExec(DynamicObject self, Object[] args, NotProvided block) {
throw new RaiseException(coreExceptions().noBlockGiven(this));
}
}
@CoreMethod(names = "class_variable_defined?", required = 1)
@NodeChildren({
@NodeChild(type = RubyNode.class, value = "module"),
@NodeChild(type = RubyNode.class, value = "name")
})
public abstract static class ClassVariableDefinedNode extends CoreMethodNode {
@CreateCast("name")
public RubyNode coerceToString(RubyNode name) {
return NameToJavaStringNodeGen.create(name);
}
@TruffleBoundary(throwsControlFlowException = true)
@Specialization
public boolean isClassVariableDefinedString(DynamicObject module, String name) {
SymbolTable.checkClassVariableName(getContext(), name, module, this);
final Object value = ModuleOperations.lookupClassVariable(module, name);
return value != null;
}
}
@CoreMethod(names = "class_variable_get", required = 1)
@NodeChildren({
@NodeChild(type = RubyNode.class, value = "module"),
@NodeChild(type = RubyNode.class, value = "name")
})
public abstract static class ClassVariableGetNode extends CoreMethodNode {
@CreateCast("name")
public RubyNode coerceToString(RubyNode name) {
return NameToJavaStringNodeGen.create(name);
}
@Specialization
@TruffleBoundary(throwsControlFlowException = true)
public Object getClassVariable(DynamicObject module, String name) {
SymbolTable.checkClassVariableName(getContext(), name, module, this);
final Object value = ModuleOperations.lookupClassVariable(module, name);
if (value == null) {
throw new RaiseException(coreExceptions().nameErrorUninitializedClassVariable(module, name, this));
} else {
return value;
}
}
}
@CoreMethod(names = "class_variable_set", required = 2, raiseIfFrozenSelf = true)
@NodeChildren({
@NodeChild(type = RubyNode.class, value = "module"),
@NodeChild(type = RubyNode.class, value = "name"),
@NodeChild(type = RubyNode.class, value = "value")
})
public abstract static class ClassVariableSetNode extends CoreMethodNode {
@CreateCast("name")
public RubyNode coerceToString(RubyNode name) {
return NameToJavaStringNodeGen.create(name);
}
@Specialization
@TruffleBoundary(throwsControlFlowException = true)
public Object setClassVariable(DynamicObject module, String name, Object value) {
SymbolTable.checkClassVariableName(getContext(), name, module, this);
ModuleOperations.setClassVariable(getContext(), module, name, value, this);
return value;
}
}
@CoreMethod(names = "class_variables")
public abstract static class ClassVariablesNode extends CoreMethodArrayArgumentsNode {
@TruffleBoundary
@Specialization
public DynamicObject getClassVariables(DynamicObject module) {
final Map<String, Object> allClassVariables = ModuleOperations.getAllClassVariables(module);
final int size = allClassVariables.size();
final Object[] store = new Object[size];
int i = 0;
for (String variable : allClassVariables.keySet()) {
store[i++] = getSymbol(variable);
}
return createArray(store, size);
}
}
@CoreMethod(names = "constants", optional = 1)
@NodeChildren({
@NodeChild(type = RubyNode.class, value = "module"),
@NodeChild(type = RubyNode.class, value = "inherit")
})
public abstract static class ConstantsNode extends CoreMethodNode {
@CreateCast("inherit")
public RubyNode coerceToBoolean(RubyNode inherit) {
return BooleanCastWithDefaultNodeGen.create(true, inherit);
}
@TruffleBoundary
@Specialization
public DynamicObject constants(DynamicObject module, boolean inherit) {
final List<DynamicObject> constantsArray = new ArrayList<>();
final Iterable<Entry<String, RubyConstant>> constants;
if (inherit) {
constants = ModuleOperations.getAllConstants(module);
} else {
constants = Layouts.MODULE.getFields(module).getConstants();
}
for (Entry<String, RubyConstant> constant : constants) {
if (!constant.getValue().isPrivate()) {
constantsArray.add(getSymbol(constant.getKey()));
}
}
Object[] objects = constantsArray.toArray(new Object[constantsArray.size()]);
return createArray(objects, objects.length);
}
}
@CoreMethod(names = "const_defined?", required = 1, optional = 1)
@NodeChildren({
@NodeChild(type = RubyNode.class, value = "module"),
@NodeChild(type = RubyNode.class, value = "name"),
@NodeChild(type = RubyNode.class, value = "inherit")
})
public abstract static class ConstDefinedNode extends CoreMethodNode {
@CreateCast("name")
public RubyNode coerceToString(RubyNode name) {
return NameToJavaStringNodeGen.create(name);
}
@CreateCast("inherit")
public RubyNode coerceToBoolean(RubyNode inherit) {
return BooleanCastWithDefaultNodeGen.create(true, inherit);
}
@TruffleBoundary
@Specialization
public boolean isConstDefined(DynamicObject module, String fullName, boolean inherit) {
return ModuleOperations.lookupScopedConstant(getContext(), module, fullName, inherit, this) != null;
}
}
@CoreMethod(names = "const_get", required = 1, optional = 1)
@NodeChildren({
@NodeChild(type = RubyNode.class, value = "module"),
@NodeChild(type = RubyNode.class, value = "name"),
@NodeChild(type = RubyNode.class, value = "inherit")
})
public abstract static class ConstGetNode extends CoreMethodNode {
@Child private RequireNode requireNode;
@Child LookupConstantNode lookupConstantNode = LookupConstantNode.create(true, true);
@Child GetConstantNode getConstantNode = GetConstantNode.create();
@CreateCast("name")
public RubyNode coerceToSymbolOrString(RubyNode name) {
return NameToSymbolOrStringNodeGen.create(null, null, name);
}
@CreateCast("inherit")
public RubyNode coerceToBoolean(RubyNode inherit) {
return BooleanCastWithDefaultNodeGen.create(true, inherit);
}
// Symbol
@Specialization(guards = { "inherit", "isRubySymbol(name)" })
public Object getConstant(VirtualFrame frame, DynamicObject module, DynamicObject name, boolean inherit) {
return getConstant(frame, module, Layouts.SYMBOL.getString(name));
}
@Specialization(guards = { "!inherit", "isRubySymbol(name)" })
public Object getConstantNoInherit(VirtualFrame frame, DynamicObject module, DynamicObject name, boolean inherit) {
return getConstantNoInherit(frame, module, Layouts.SYMBOL.getString(name), this);
}
// String
@Specialization(guards = { "inherit", "isRubyString(name)", "!isScoped(name)" })
public Object getConstantString(VirtualFrame frame, DynamicObject module, DynamicObject name, boolean inherit) {
return getConstant(frame, module, name.toString());
}
@Specialization(guards = { "!inherit", "isRubyString(name)", "!isScoped(name)" })
public Object getConstantNoInheritString(VirtualFrame frame, DynamicObject module, DynamicObject name, boolean inherit) {
return getConstantNoInherit(frame, module, name.toString(), this);
}
// Scoped String
@Specialization(guards = {"isRubyString(fullName)", "isScoped(fullName)"})
public Object getConstantScoped(DynamicObject module, DynamicObject fullName, boolean inherit) {
return getConstantScoped(module, fullName.toString(), inherit);
}
private Object getConstant(VirtualFrame frame, Object module, String name) {
final RubyConstant constant = lookupConstantNode.lookupConstant(frame, module, name);
return getConstantNode.executeGetConstant(frame, module, name, constant, lookupConstantNode);
}
private Object getConstantNoInherit(VirtualFrame frame, DynamicObject module, String name, Node currentNode) {
RubyConstant constant = ModuleOperations.lookupConstantWithInherit(getContext(), module, name, false, currentNode);
if (constant == null) {
// Call const_missing
return getConstantNode.executeGetConstant(frame, module, name, null, lookupConstantNode);
} else {
if (constant.isAutoload()) {
loadAutoloadedConstant(frame, constant);
constant = ModuleOperations.lookupConstantWithInherit(getContext(), module, name, false, currentNode);
}
return constant.getValue();
}
}
@TruffleBoundary
private Object getConstantScoped(DynamicObject module, String fullName, boolean inherit) {
RubyConstant constant = ModuleOperations.lookupScopedConstant(getContext(), module, fullName, inherit, this);
if (constant == null) {
throw new RaiseException(coreExceptions().nameErrorUninitializedConstant(module, fullName, this));
} else {
return constant.getValue();
}
}
@TruffleBoundary
boolean isScoped(DynamicObject name) {
assert RubyGuards.isRubyString(name);
// TODO (eregon, 27 May 2015): Any way to make this efficient?
return name.toString().contains("::");
}
private void loadAutoloadedConstant(VirtualFrame frame, RubyConstant constant) {
if (requireNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
requireNode = insert(RequireNode.create());
}
final String feature = StringOperations.getString((DynamicObject) constant.getValue());
requireNode.executeRequire(frame, feature);
}
}
@CoreMethod(names = "const_missing", required = 1)
@NodeChildren({
@NodeChild(type = RubyNode.class, value = "module"),
@NodeChild(type = RubyNode.class, value = "name")
})
public abstract static class ConstMissingNode extends CoreMethodNode {
@CreateCast("name")
public RubyNode coerceToString(RubyNode name) {
return NameToJavaStringNodeGen.create(name);
}
@Specialization
public Object constMissing(DynamicObject module, String name) {
throw new RaiseException(coreExceptions().nameErrorUninitializedConstant(module, name, this));
}
}
@CoreMethod(names = "const_set", required = 2)
@NodeChildren({
@NodeChild(type = RubyNode.class, value = "module"),
@NodeChild(type = RubyNode.class, value = "name"),
@NodeChild(type = RubyNode.class, value = "value")
})
public abstract static class ConstSetNode extends CoreMethodNode {
@CreateCast("name")
public RubyNode coerceToString(RubyNode name) {
return NameToJavaStringNodeGen.create(name);
}
@TruffleBoundary
@Specialization
public Object setConstant(DynamicObject module, String name, Object value) {
if (!Identifiers.isValidConstantName19(name)) {
throw new RaiseException(coreExceptions().nameError(StringUtils.format("wrong constant name %s", name), module, name, this));
}
Layouts.MODULE.getFields(module).setConstant(getContext(), this, name, value);
return value;
}
}
@CoreMethod(names = "define_method", needsBlock = true, required = 1, optional = 1, visibility = Visibility.PRIVATE)
@NodeChildren({
@NodeChild(type = RubyNode.class, value = "module"),
@NodeChild(type = RubyNode.class, value = "name"),
@NodeChild(type = RubyNode.class, value = "proc"),
@NodeChild(type = RubyNode.class, value = "block")
})
public abstract static class DefineMethodNode extends CoreMethodNode {
@Child AddMethodNode addMethodNode;
public DefineMethodNode(RubyContext context, SourceSection sourceSection) {
super(context, sourceSection);