forked from IronLanguages/main
/
RubyContext.cs
3112 lines (2540 loc) · 122 KB
/
RubyContext.cs
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) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using MSA = System.Linq.Expressions;
#else
using MSA = Microsoft.Scripting.Ast;
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading;
using IronRuby.Builtins;
using IronRuby.Compiler;
using IronRuby.Compiler.Ast;
using IronRuby.Compiler.Generation;
using IronRuby.Hosting;
using IronRuby.Runtime.Calls;
using IronRuby.Runtime.Conversions;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using System.Collections.ObjectModel;
using System.Globalization;
namespace IronRuby.Runtime {
[ReflectionCached]
public sealed class RubyContext : LanguageContext {
#region Constants
internal static readonly Guid RubyLanguageGuid = new Guid("F03C4640-DABA-473f-96F1-391400714DAB");
private static readonly Guid LanguageVendor_Microsoft = new Guid(-1723120188, -6423, 0x11d2, 0x90, 0x3f, 0, 0xc0, 0x4f, 0xa3, 2, 0xa1);
private static int _RuntimeIdGenerator = 0;
// MRI compliance:
public string/*!*/ MriVersion {
get { return "1.9.2"; }
}
public string/*!*/ StandardLibraryVersion {
get { return "1.9.1"; }
}
public string/*!*/ MriReleaseDate {
get { return "2010-08-18"; }
}
public int MriPatchLevel {
get { return 0; }
}
public const string BinDirEnvironmentVariable = "IRONRUBY_11";
// IronRuby:
public const string IronRubyInformationalVersion = "1.1.4";
#if !SILVERLIGHT
public const string/*!*/ IronRubyVersionString = "1.1.4.0";
public static readonly Version IronRubyVersion = new Version(1, 1, 4, 0);
#else
public const string/*!*/ IronRubyVersionString = "1.1.1304.0";
public static readonly Version IronRubyVersion = new Version(1, 1, 1304, 0);
#endif
internal const string/*!*/ IronRubyDisplayName = "IronRuby";
internal const string/*!*/ IronRubyNames = "IronRuby;Ruby;rb";
internal const string/*!*/ IronRubyFileExtensions = ".rb";
#endregion
// TODO: remove
internal static RubyContext _Default;
private readonly int _runtimeId;
private readonly RubyScope/*!*/ _emptyScope;
private RubyOptions/*!*/ _options;
private readonly TopNamespaceTracker _namespaces;
private readonly Loader/*!*/ _loader;
private readonly Scope/*!*/ _globalScope;
private readonly RubyMetaBinderFactory/*!*/ _metaBinderFactory;
private readonly RubyBinder _binder;
private DynamicDelegateCreator _delegateCreator;
private RubyService _rubyService;
#region Global Variables (thread-safe access)
/// <summary>
/// $0
/// </summary>
public MutableString CommandLineProgramPath { get; set; }
/// <summary>
/// $? of type Process::Status
/// </summary>
[ThreadStatic]
private static object _childProcessExitStatus;
/// <summary>
/// $/, $-O
/// </summary>
private MutableString _inputSeparator;
/// <summary>
/// $\
/// </summary>
private MutableString _outputSeparator;
/// <summary>
/// $;, $-F
/// </summary>
private object _stringSeparator;
/// <summary>
/// $,
/// </summary>
private MutableString _itemSeparator;
private readonly Dictionary<string/*!*/, GlobalVariable>/*!*/ _globalVariables;
public object/*!*/ GlobalVariablesLock { get { return _globalVariables; } } // does not need to use _typeSystemLock as operations on _symbols are all simple
// not thread safe: use GlobalVariablesLock to synchronize access to the variables:
public IEnumerable<KeyValuePair<string, GlobalVariable>>/*!*/ GlobalVariables {
get { return _globalVariables; }
}
#endregion
#region Random Number Generator
private readonly object _randomNumberGeneratorLock = new object();
private Random _randomNumberGenerator; // lazy
private object _randomNumberGeneratorSeed = ScriptingRuntimeHelpers.Int32ToObject(0);
public object RandomNumberGeneratorSeed {
get { return _randomNumberGeneratorSeed; }
}
public void SeedRandomNumberGenerator(IntegerValue value) {
lock (_randomNumberGeneratorLock) {
_randomNumberGenerator = new Random(value.IsFixnum ? value.Fixnum : value.Bignum.GetHashCode());
_randomNumberGeneratorSeed = value.ToObject();
}
}
public Random/*!*/ RandomNumberGenerator {
get {
if (_randomNumberGenerator == null) {
lock (_randomNumberGeneratorLock) {
if (_randomNumberGenerator == null) {
_randomNumberGenerator = new Random();
}
}
}
return _randomNumberGenerator;
}
}
#endregion
#region Threading
#if FEATURE_THREAD
// Thread#main
private readonly Thread _mainThread;
// Thread#critical=
// We just need a bool. But we store the Thread object for easier debugging if there is a hang
private Thread _criticalThread;
private readonly object _criticalMonitor = new object();
public object CriticalMonitor {
get { return _criticalMonitor; }
}
public Thread MainThread {
get { return _mainThread; }
}
public Thread CriticalThread {
get { return _criticalThread; }
set { _criticalThread = value; }
}
#endif
#endregion
#region Tracing
private readonly RubyInputProvider/*!*/ _inputProvider;
private Proc _traceListener;
[ThreadStatic]
private bool _traceListenerSuspended;
#if FEATURE_FILESYSTEM
private readonly Stopwatch _upTime;
#endif
// TODO: thread-safety
internal Action<Expression, MSA.DynamicExpression> CallSiteCreated { get; set; }
#endregion
#region Look-aside tables
/// <summary>
/// Maps CLR types to Ruby classes/modules.
/// Doesn't contain classes defined in Ruby.
/// </summary>
private readonly Dictionary<Type, RubyModule>/*!*/ _moduleCache;
/// <summary>Warning:
/// ModuleCacheLock and ClassHierarchyLock sometimes interact.
/// If both are to be locked, the locking order must always be:
/// First acquire ClassHierarchyLock, Second acquire ModuleCacheLock</summary>
private object ModuleCacheLock { get { return _moduleCache; } }
/// <summary>
/// Maps CLR namespace trackers to Ruby modules.
/// </summary>
private readonly Dictionary<NamespaceTracker, RubyModule>/*!*/ _namespaceCache;
private object NamespaceCacheLock { get { return _namespaceCache; } } // safe to lock as operations on _namespaceCache are all simple
// Maps objects to InstanceData. The keys store weak references to the objects.
// Objects are compared by reference (identity).
// An entry can be removed as soon as the key object becomes unreachable.
private readonly WeakTable<object, RubyInstanceData>/*!*/ _referenceTypeInstanceData;
private object/*!*/ ReferenceTypeInstanceDataLock { get { return _referenceTypeInstanceData; } } // safe to lock as operations on _referenceTypeInstanceData are all simple
// Maps values to InstanceData. The keys store value representatives.
// All objects that has the same value (value-equality) map to the same InstanceData.
// Entries cannot be ever freed since anytime in future one may create a new object whose value has already been mapped to InstanceData.
private readonly Dictionary<object, RubyInstanceData>/*!*/ _valueTypeInstanceData;
private object/*!*/ ValueTypeInstanceDataLock { get { return _valueTypeInstanceData; } } // safe to lock as operations on _valueTypeInstanceData are all simple
// not thread-safe:
private readonly RubyInstanceData/*!*/ _nilInstanceData = new RubyInstanceData(RubyUtils.NilObjectId);
#endregion
#region Class Hierarchy
public IDisposable/*!*/ ClassHierarchyLocker() {
return _classHierarchyLock.CreateLocker();
}
public IDisposable/*!*/ ClassHierarchyUnlocker() {
return _classHierarchyLock.CreateUnlocker();
}
private readonly CheckedMonitor/*!*/ _classHierarchyLock = new CheckedMonitor();
[Emitted]
public int ConstantAccessVersion = 1;
[Conditional("DEBUG")]
internal void RequiresClassHierarchyLock() {
Debug.Assert(_classHierarchyLock.IsLocked, "Code can only be executed while holding class hierarchy lock.");
}
// classes used by runtime (we need to update initialization generator if any of these are added):
private RubyClass/*!*/ _basicObjectClass;
private RubyModule/*!*/ _kernelModule;
private RubyClass/*!*/ _objectClass;
private RubyClass/*!*/ _classClass;
private RubyClass/*!*/ _moduleClass;
private RubyClass/*!*/ _nilClass;
private RubyClass/*!*/ _trueClass;
private RubyClass/*!*/ _falseClass;
private RubyClass/*!*/ _exceptionClass;
private RubyClass _standardErrorClass;
private RubyClass _comObjectClass;
private Action<RubyModule>/*!*/ _mainSingletonTrait;
// internally set by Initializer:
public RubyClass/*!*/ BasicObjectClass { get { return _basicObjectClass; } }
public RubyModule/*!*/ KernelModule { get { return _kernelModule; } }
public RubyClass/*!*/ ObjectClass { get { return _objectClass; } }
public RubyClass/*!*/ ClassClass { get { return _classClass; } set { _classClass = value; } }
public RubyClass/*!*/ ModuleClass { get { return _moduleClass; } set { _moduleClass = value; } }
public RubyClass/*!*/ NilClass { get { return _nilClass; } set { _nilClass = value; } }
public RubyClass/*!*/ TrueClass { get { return _trueClass; } set { _trueClass = value; } }
public RubyClass/*!*/ FalseClass { get { return _falseClass; } set { _falseClass = value; } }
public RubyClass ExceptionClass { get { return _exceptionClass; } set { _exceptionClass = value; } }
public RubyClass StandardErrorClass { get { return _standardErrorClass; } set { _standardErrorClass = value; } }
internal RubyClass ComObjectClass {
get {
#if FEATURE_COM
if (_comObjectClass == null) {
GetOrCreateClass(TypeUtils.ComObjectType);
}
#endif
return _comObjectClass;
}
}
// Set of names that method_missing defined on any module was resolved for and that are cached. Lazy init.
//
// Note: We used to have this set per module but that doesn't work - see unit test MethodCallCaching_MethodMissing4.
// Whenever a method is added to a class C we would need to traverse all its subclasses to see if any of them
// has the added method in its MissingMethodsCachedInSites table.
// TODO: Could we optimize this search? If so we could also free the per-module set if mm is removed.
internal HashSet<string> MissingMethodsCachedInSites { get; set; }
#endregion
#region Properties
public PlatformAdaptationLayer/*!*/ Platform {
get { return DomainManager.Platform; }
}
public override LanguageOptions Options {
get { return _options; }
}
public RubyOptions RubyOptions {
get { return _options; }
}
internal RubyScope/*!*/ EmptyScope {
get { return _emptyScope; }
}
public MutableString InputSeparator {
get { return _inputSeparator; }
set { _inputSeparator = value; }
}
public MutableString OutputSeparator {
get { return _outputSeparator; }
set { _outputSeparator = value; }
}
public object StringSeparator {
get { return _stringSeparator; }
set { _stringSeparator = value; }
}
public MutableString ItemSeparator {
get { return _itemSeparator; }
set { _itemSeparator = value; }
}
public Proc TraceListener {
get { return _traceListener; }
set { _traceListener = value; }
}
public RubyInputProvider/*!*/ InputProvider {
get { return _inputProvider; }
}
public object ChildProcessExitStatus {
get { return _childProcessExitStatus; }
set { _childProcessExitStatus = value; }
}
public Scope/*!*/ TopGlobalScope {
get { return _globalScope; }
}
internal RubyMetaBinderFactory/*!*/ MetaBinderFactory {
get { return _metaBinderFactory; }
}
public Loader/*!*/ Loader {
get { return _loader; }
}
public bool ShowCls {
get { return false; }
}
public EqualityComparer/*!*/ EqualityComparer {
get {
if (_equalityComparer == null) {
_equalityComparer = new EqualityComparer(this);
}
return _equalityComparer;
}
}
private EqualityComparer _equalityComparer;
public override Version LanguageVersion {
get { return IronRubyVersion; }
}
public override Guid LanguageGuid {
get { return RubyLanguageGuid; }
}
public override Guid VendorGuid {
get { return LanguageVendor_Microsoft; }
}
public int RuntimeId {
get { return _runtimeId; }
}
internal TopNamespaceTracker/*!*/ Namespaces {
get { return _namespaces; }
}
public object Verbose { get; set; }
private RubyEncoding/*!*/ _defaultExternalEncoding;
public RubyEncoding/*!*/ DefaultExternalEncoding {
get { return _defaultExternalEncoding; }
set {
ContractUtils.RequiresNotNull(value, "value");
_defaultExternalEncoding = value;
}
}
public RubyEncoding DefaultInternalEncoding { get; set; }
#endregion
#region Initialization
public RubyContext(ScriptDomainManager/*!*/ manager, IDictionary<string, object> options)
: base(manager) {
ContractUtils.RequiresNotNull(manager, "manager");
_options = new RubyOptions(options);
_runtimeId = Interlocked.Increment(ref _RuntimeIdGenerator);
#if FEATURE_FILESYSTEM
_upTime = new Stopwatch();
_upTime.Start();
#endif
_binder = new RubyBinder(this);
_symbols = new Dictionary<MutableString, RubySymbol>();
_metaBinderFactory = new RubyMetaBinderFactory(this);
_runtimeErrorSink = new RuntimeErrorSink(this);
_equalityComparer = new EqualityComparer(this);
_globalVariables = new Dictionary<string, GlobalVariable>();
_moduleCache = new Dictionary<Type, RubyModule>();
_namespaceCache = new Dictionary<NamespaceTracker, RubyModule>();
_referenceTypeInstanceData = new WeakTable<object, RubyInstanceData>();
_valueTypeInstanceData = new Dictionary<object, RubyInstanceData>();
_inputProvider = new RubyInputProvider(this, _options.Arguments, _options.LocaleEncoding);
_defaultExternalEncoding = _options.DefaultEncoding ?? _options.LocaleEncoding;
_globalScope = DomainManager.Globals;
_loader = new Loader(this);
_emptyScope = new RubyTopLevelScope(this);
_currentException = null;
_currentSafeLevel = 0;
_childProcessExitStatus = null;
_inputSeparator = MutableString.CreateAscii("\n");
_outputSeparator = null;
_stringSeparator = null;
_itemSeparator = null;
#if FEATURE_THREAD
_mainThread = Thread.CurrentThread;
#endif
if (_options.MainFile != null) {
CommandLineProgramPath = EncodePath(_options.MainFile);
}
if (_options.Verbosity <= 0) {
Verbose = null;
} else if (_options.Verbosity == 1) {
Verbose = ScriptingRuntimeHelpers.False;
} else {
Verbose = ScriptingRuntimeHelpers.True;
}
_namespaces = new TopNamespaceTracker(manager);
manager.AssemblyLoaded += new EventHandler<AssemblyLoadedEventArgs>((_, e) => AssemblyLoaded(e.Assembly));
foreach (Assembly asm in manager.GetLoadedAssemblyList()) {
AssemblyLoaded(asm);
}
// TODO:
Interlocked.CompareExchange(ref _Default, this, null);
_loader.LoadBuiltins();
Debug.Assert(_exceptionClass != null && _standardErrorClass != null && _nilClass != null);
Debug.Assert(_classClass != null && _moduleClass != null);
// needs to run before globals and constants are initialized:
InitializeFileDescriptors(DomainManager.SharedIO);
InitializeGlobalConstants();
InitializeGlobalVariables();
}
internal RubyBinder/*!*/ Binder {
get { return _binder; }
}
/// <summary>
/// Clears thread static variables.
/// </summary>
internal static void ClearThreadStatics() {
_currentException = null;
}
private void InitializeGlobalVariables() {
// special variables:
Runtime.GlobalVariables.DefineVariablesNoLock(this);
// TODO:
// $-a
// $F
// $-i
// $-l
// $-p
// $?
// $0
DefineGlobalVariableNoLock("PROGRAM_NAME", Runtime.GlobalVariables.CommandLineProgramPath);
DefineGlobalVariableNoLock("stdin", Runtime.GlobalVariables.InputStream);
DefineGlobalVariableNoLock("stdout", Runtime.GlobalVariables.OutputStream);
DefineGlobalVariableNoLock("defout", Runtime.GlobalVariables.OutputStream);
DefineGlobalVariableNoLock("stderr", Runtime.GlobalVariables.ErrorOutputStream);
DefineGlobalVariableNoLock("LOADED_FEATURES", Runtime.GlobalVariables.LoadedFiles);
DefineGlobalVariableNoLock("LOAD_PATH", Runtime.GlobalVariables.LoadPath);
DefineGlobalVariableNoLock("-I", Runtime.GlobalVariables.LoadPath);
DefineGlobalVariableNoLock("-O", Runtime.GlobalVariables.InputSeparator);
DefineGlobalVariableNoLock("-F", Runtime.GlobalVariables.StringSeparator);
DefineGlobalVariableNoLock("FILENAME", Runtime.GlobalVariables.InputFileName);
GlobalVariableInfo debug = new GlobalVariableInfo(DomainManager.Configuration.DebugMode || RubyOptions.DebugVariable);
DefineGlobalVariableNoLock("VERBOSE", Runtime.GlobalVariables.Verbose);
DefineGlobalVariableNoLock("-v", Runtime.GlobalVariables.Verbose);
DefineGlobalVariableNoLock("-w", Runtime.GlobalVariables.Verbose);
DefineGlobalVariableNoLock("DEBUG", debug);
DefineGlobalVariableNoLock("-d", debug);
DefineGlobalVariableNoLock("KCODE", Runtime.GlobalVariables.KCode);
DefineGlobalVariableNoLock("-K", Runtime.GlobalVariables.KCode);
DefineGlobalVariableNoLock("SAFE", Runtime.GlobalVariables.SafeLevel);
#if FEATURE_PROCESS
try {
TrySetCurrentProcessVariables();
} catch (SecurityException) {
// nop
}
#endif
}
#if FEATURE_PROCESS
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
private void TrySetCurrentProcessVariables() {
Process process = Process.GetCurrentProcess();
DefineGlobalVariableNoLock(Symbols.CurrentProcessId, new ReadOnlyGlobalVariableInfo(process.Id));
}
#endif
private void InitializeGlobalConstants() {
Debug.Assert(_objectClass != null);
MutableString version = MutableString.CreateAscii(MriVersion);
MutableString platform = MakePlatformString();
MutableString releaseDate = MutableString.CreateAscii(MriReleaseDate);
MutableString rubyEngine = MutableString.CreateAscii("ironruby");
using (ClassHierarchyLocker()) {
RubyClass obj = _objectClass;
obj.SetConstantNoMutateNoLock("RUBY_ENGINE", rubyEngine);
obj.SetConstantNoMutateNoLock("RUBY_VERSION", version);
obj.SetConstantNoMutateNoLock("RUBY_PATCHLEVEL", MriPatchLevel);
obj.SetConstantNoMutateNoLock("RUBY_PLATFORM", platform);
obj.SetConstantNoMutateNoLock("RUBY_RELEASE_DATE", releaseDate);
obj.SetConstantNoMutateNoLock("RUBY_DESCRIPTION", MutableString.CreateAscii(MakeDescriptionString()));
obj.SetConstantNoMutateNoLock("VERSION", version);
obj.SetConstantNoMutateNoLock("PLATFORM", platform);
obj.SetConstantNoMutateNoLock("RELEASE_DATE", releaseDate);
obj.SetConstantNoMutateNoLock("IRONRUBY_VERSION", MutableString.CreateAscii(RubyContext.IronRubyVersionString));
obj.SetConstantNoMutateNoLock("STDIN", StandardInput);
obj.SetConstantNoMutateNoLock("STDOUT", StandardOutput);
obj.SetConstantNoMutateNoLock("STDERR", StandardErrorOutput);
ConstantStorage argf;
if (obj.TryGetConstantNoAutoloadCheck("ARGF", out argf)) {
_inputProvider.Singleton = argf.Value;
}
obj.SetConstantNoMutateNoLock("ARGV", _inputProvider.CommandLineArguments);
// Hash
// SCRIPT_LINES__
}
}
public static string/*!*/ MakeDescriptionString() {
return String.Format(CultureInfo.InvariantCulture, "IronRuby {0} on {1}", IronRubyVersion, MakeRuntimeDesriptionString());
}
internal static string MakeRuntimeDesriptionString() {
Type mono = typeof(object).GetTypeInfo().Assembly.GetType("Mono.Runtime");
return mono != null ?
(string)mono.GetMethod("GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, null)
#if WIN8
: "Windows Runtime";
#else
: String.Format(CultureInfo.InvariantCulture, ".NET {0}", Environment.Version);
#endif
}
private static MutableString/*!*/ MakePlatformString() {
#if WIN8
return MutableString.CreateAscii("Windows Runtime");
#elif WP75
return MutableString.CreateAscii("Windows Phone");
#else
switch (Environment.OSVersion.Platform) {
case PlatformID.MacOSX:
return MutableString.CreateAscii("i386-darwin");
case PlatformID.Unix:
return MutableString.CreateAscii("i386-linux");
case PlatformID.Win32NT:
case PlatformID.Win32S:
case PlatformID.Win32Windows:
return MutableString.CreateAscii("i386-mswin32");
default:
return MutableString.CreateAscii("unknown");
}
#endif
}
private void InitializeFileDescriptors(SharedIO/*!*/ io) {
Debug.Assert(_fileDescriptors.Count == 0);
Stream stream = new ConsoleStream(io, ConsoleStreamType.Input);
StandardInput = new RubyIO(this, stream, AllocateFileDescriptor(stream), IOMode.ReadOnly);
stream = new ConsoleStream(io, ConsoleStreamType.Output);
StandardOutput = new RubyIO(this, stream, AllocateFileDescriptor(stream), IOMode.WriteOnly | IOMode.WriteAppends);
stream = new ConsoleStream(io, ConsoleStreamType.ErrorOutput);
StandardErrorOutput = new RubyIO(this, stream, AllocateFileDescriptor(stream), IOMode.WriteOnly | IOMode.WriteAppends);
}
// TODO: internal
public void RegisterPrimitives(
Action<RubyModule>/*!*/ mainSingletonTrait,
Action<RubyModule>/*!*/ basicObjectInstanceTrait,
Action<RubyModule>/*!*/ basicObjectClassTrait,
Action<RubyModule> basicObjectConstantsInitializer,
Action<RubyModule>/*!*/ kernelInstanceTrait,
Action<RubyModule>/*!*/ kernelClassTrait,
Action<RubyModule> kernelConstantsInitializer,
Action<RubyModule>/*!*/ objectInstanceTrait,
Action<RubyModule>/*!*/ objectClassTrait,
Action<RubyModule> objectConstantsInitializer,
Action<RubyModule>/*!*/ moduleInstanceTrait,
Action<RubyModule>/*!*/ moduleClassTrait,
Action<RubyModule> moduleConstantsInitializer,
Action<RubyModule>/*!*/ classInstanceTrait,
Action<RubyModule>/*!*/ classClassTrait,
Action<RubyModule> classConstantsInitializer) {
Assert.NotNull(mainSingletonTrait, basicObjectInstanceTrait, basicObjectClassTrait);
Assert.NotNull(objectInstanceTrait, kernelInstanceTrait, moduleInstanceTrait, classInstanceTrait);
Assert.NotNull(objectClassTrait, kernelClassTrait, moduleClassTrait, classClassTrait);
_mainSingletonTrait = mainSingletonTrait;
// inheritance hierarchy:
//
// Class
// ^
// BasicObject -> BasicObject'
// ^ ^
// Object -> Object'
// ^ ^
// Module -> Module'
// ^ ^
// Class -> Class'
// ^
// Object'
//
// only Object should expose CLR methods:
TypeTracker objectTracker = TypeTracker.GetTypeTracker(typeof(object));
var moduleFactories = new Delegate[] {
new Func<RubyScope, BlockParam, RubyClass, object>(RubyModule.CreateAnonymousModule),
};
var classFactories = new Delegate[] {
new Func<RubyScope, BlockParam, RubyClass, RubyClass, object>(RubyClass.CreateAnonymousClass),
};
// locks to comply with lock requirements:
using (ClassHierarchyLocker()) {
_basicObjectClass = new RubyClass(this, Symbols.BasicObject, null, null, basicObjectInstanceTrait, basicObjectConstantsInitializer, null, null, null, null, null, false, false, ModuleRestrictions.Builtin & ~ModuleRestrictions.NoOverrides);
_kernelModule = new RubyModule(this, Symbols.Kernel, kernelInstanceTrait, kernelConstantsInitializer, null, null, null, ModuleRestrictions.Builtin);
_objectClass = new RubyClass(this, Symbols.Object, objectTracker.Type, null, objectInstanceTrait, objectConstantsInitializer, null, _basicObjectClass, new[] { _kernelModule }, objectTracker, null, false, false, ModuleRestrictions.Builtin & ~ModuleRestrictions.NoOverrides);
_moduleClass = new RubyClass(this, Symbols.Module, typeof(RubyModule), null, moduleInstanceTrait, moduleConstantsInitializer, moduleFactories, _objectClass, null, null, null, false, false, ModuleRestrictions.Builtin);
_classClass = new RubyClass(this, Symbols.Class, typeof(RubyClass), null, classInstanceTrait, classConstantsInitializer, classFactories, _moduleClass, null, null, null, false, false, ModuleRestrictions.Builtin);
_basicObjectClass.InitializeImmediateClass(_basicObjectClass.CreateSingletonClass(_classClass, basicObjectClassTrait));
_objectClass.InitializeImmediateClass(_objectClass.CreateSingletonClass(_basicObjectClass.ImmediateClass, objectClassTrait));
_moduleClass.InitializeImmediateClass(_moduleClass.CreateSingletonClass(_objectClass.ImmediateClass, moduleClassTrait));
_classClass.InitializeImmediateClass(_classClass.CreateSingletonClass(_moduleClass.ImmediateClass, classClassTrait));
_moduleClass.InitializeDummySingleton();
_classClass.InitializeDummySingleton();
_basicObjectClass.ImmediateClass.InitializeImmediateClass(_classClass.GetDummySingletonClass());
_objectClass.ImmediateClass.InitializeImmediateClass(_classClass.GetDummySingletonClass());
_moduleClass.ImmediateClass.InitializeImmediateClass(_classClass.GetDummySingletonClass());
_classClass.ImmediateClass.InitializeImmediateClass(_classClass.GetDummySingletonClass());
_kernelModule.InitializeImmediateClass(_moduleClass, kernelClassTrait);
_objectClass.SetConstantNoMutateNoLock(_basicObjectClass.Name, _basicObjectClass);
_objectClass.SetConstantNoMutateNoLock(_moduleClass.Name, _moduleClass);
_objectClass.SetConstantNoMutateNoLock(_classClass.Name, _classClass);
_objectClass.SetConstantNoMutateNoLock(_objectClass.Name, _objectClass);
_objectClass.SetConstantNoMutateNoLock(_kernelModule.Name, _kernelModule);
}
AddModuleToCacheNoLock(typeof(BasicObject), _basicObjectClass);
AddModuleToCacheNoLock(typeof(Kernel), _kernelModule);
AddModuleToCacheNoLock(objectTracker.Type, _objectClass);
AddModuleToCacheNoLock(typeof(RubyObject), _objectClass);
AddModuleToCacheNoLock(_moduleClass.GetUnderlyingSystemType(), _moduleClass);
AddModuleToCacheNoLock(_classClass.GetUnderlyingSystemType(), _classClass);
}
#endregion
#region CLR Types and Namespaces
private void AssemblyLoaded(Assembly/*!*/ assembly) {
_namespaces.LoadAssembly(assembly);
AddExtensionAssembly(assembly);
}
internal void AddModuleToCacheNoLock(Type/*!*/ type, RubyModule/*!*/ module) {
Assert.NotNull(type, module);
_moduleCache.Add(type, module);
}
internal void AddNamespaceToCacheNoLock(NamespaceTracker/*!*/ namespaceTracker, RubyModule/*!*/ module) {
Assert.NotNull(namespaceTracker, module);
_namespaceCache.Add(namespaceTracker, module);
}
internal RubyModule/*!*/ GetOrCreateModule(NamespaceTracker/*!*/ tracker) {
Assert.NotNull(tracker);
lock (ModuleCacheLock) {
return GetOrCreateModuleNoLock(tracker);
}
}
internal bool TryGetModule(NamespaceTracker/*!*/ namespaceTracker, out RubyModule result) {
lock (NamespaceCacheLock) {
return _namespaceCache.TryGetValue(namespaceTracker, out result);
}
}
internal RubyModule/*!*/ GetOrCreateModule(Type/*!*/ moduleType) {
Debug.Assert(RubyModule.IsModuleType(moduleType));
lock (ModuleCacheLock) {
return GetOrCreateModuleNoLock(moduleType);
}
}
public bool TryGetModule(Type/*!*/ type, out RubyModule result) {
lock (ModuleCacheLock) {
return _moduleCache.TryGetValue(type, out result);
}
}
internal bool TryGetModuleNoLock(Type/*!*/ type, out RubyModule result) {
return _moduleCache.TryGetValue(type, out result);
}
internal bool TryGetClassNoLock(Type/*!*/ type, out RubyClass result) {
RubyModule module;
if (_moduleCache.TryGetValue(type, out module)) {
result = module as RubyClass;
if (result == null) {
throw new InvalidOperationException("Specified type doesn't represent a class");
}
return true;
} else {
result = null;
return false;
}
}
internal RubyClass/*!*/ GetOrCreateClass(Type/*!*/ type) {
using (ClassHierarchyLocker()) {
lock (ModuleCacheLock) {
return GetOrCreateClassNoLock(type);
}
}
}
private RubyModule/*!*/ GetOrCreateModuleNoLock(NamespaceTracker/*!*/ tracker) {
Assert.NotNull(tracker);
RubyModule result;
if (_namespaceCache.TryGetValue(tracker, out result)) {
return result;
}
result = CreateModule(GetQualifiedName(tracker), null, null, null, null, tracker, null, ModuleRestrictions.None);
_namespaceCache[tracker] = result;
return result;
}
private RubyModule/*!*/ GetOrCreateModuleNoLock(Type/*!*/ moduleType) {
Debug.Assert(RubyModule.IsModuleType(moduleType));
RubyModule result;
if (_moduleCache.TryGetValue(moduleType, out result)) {
return result;
}
TypeTracker tracker = (TypeTracker)TypeTracker.FromMemberInfo(moduleType.GetTypeInfo());
RubyModule[] mixins;
if (moduleType.IsGenericType() && !moduleType.IsGenericTypeDefinition()) {
// I<T0..Tn> mixes in its generic definition I<,..,>
mixins = new[] { GetOrCreateModuleNoLock(moduleType.GetGenericTypeDefinition()) };
} else {
mixins = null;
}
result = CreateModule(GetQualifiedNameNoLock(moduleType), null, null, null, mixins, null, tracker, ModuleRestrictions.None);
_moduleCache[moduleType] = result;
return result;
}
// Requires hierarchy lock and module cache lock
private RubyClass/*!*/ GetOrCreateClassNoLock(Type/*!*/ type) {
RequiresClassHierarchyLock();
Debug.Assert(!RubyModule.IsModuleType(type));
RubyClass result;
if (TryGetClassNoLock(type, out result)) {
return result;
}
RubyClass baseClass;
if (type.IsByRef) {
baseClass = _objectClass;
} else {
baseClass = GetOrCreateClassNoLock(type.GetBaseType());
}
TypeTracker tracker = (TypeTracker)TypeTracker.FromMemberInfo(type.GetTypeInfo());
RubyModule[] clrMixins = GetClrMixinsNoLock(type);
RubyModule[] expandedMixins;
if (clrMixins != null) {
// this part requires the hierarchy lock. The rest just requires ModuleCacheLock
expandedMixins = RubyModule.ExpandMixinsNoLock(baseClass, clrMixins);
} else {
expandedMixins = RubyModule.EmptyArray;
}
result = CreateClass(
GetQualifiedNameNoLock(type), type, null, null, null, null, null,
baseClass, expandedMixins, tracker, null, false, false, ModuleRestrictions.None
);
if (TypeUtils.IsComObjectType(type)) {
_comObjectClass = result;
}
_moduleCache[type] = result;
return result;
}
/// <summary>
/// An interface is mixed into the type that implements it.
/// A generic type definition is mixed into its instantiations.
///
/// In both cases these modules don't themselves contribute any callable CLR methods
/// yet they might contribute CLR extension methods and Ruby methods defined on them.
/// </summary>
private RubyModule[] GetClrMixinsNoLock(Type/*!*/ type) {
List<RubyModule> modules = new List<RubyModule>();
if (type.IsGenericType() && !type.IsGenericTypeDefinition()) {
modules.Add(GetOrCreateModuleNoLock(type.GetGenericTypeDefinition()));
}
if (type.IsArray) {
if (type.GetArrayRank() > 1) {
RubyModule module;
if (TryGetModuleNoLock(typeof(MultiDimensionalArray), out module)) {
modules.Add(module);
}
}
} else if (type.IsEnum()) {
if (type.GetTypeInfo().IsDefined(typeof(FlagsAttribute), false)) {
RubyModule module;
if (TryGetModuleNoLock(typeof(FlagEnumeration), out module)) {
modules.Add(module);
}
}
}
foreach (Type iface in ReflectionUtils.GetDeclaredInterfaces(type)) {
modules.Add(GetOrCreateModuleNoLock(iface));
}
return modules.Count > 0 ? modules.ToArray() : null;
}
#endregion
#region CLR Extension Methods
private readonly object ExtensionsLock = new object();
// List of assemblies that might include extension methods but whose processing was delayed until the first call of use_clr_extensions.
// Null once use_clr_extensions has been called.
private List<Assembly> _potentialExtensionAssemblies = new List<Assembly>();
// A list of extension methods that are available for activation. Grouped by a declaring namespace.
// Value is null if the namepsace has been activated.
private Dictionary<string, List<IEnumerable<ExtensionMethodInfo>>> _availableExtensions;
private void AddExtensionAssembly(Assembly/*!*/ assembly) {
if (_potentialExtensionAssemblies != null) {
lock (ExtensionsLock) {
if (_potentialExtensionAssemblies != null) {
_potentialExtensionAssemblies.Add(assembly);
return;
}
}
}
LoadExtensions(ReflectionUtils.GetVisibleExtensionMethodGroups(assembly, true));
}
private void LoadExtensions(IEnumerable<KeyValuePair<string, IEnumerable<ExtensionMethodInfo>>>/*!*/ extensionMethodGroups) {
List<IEnumerable<ExtensionMethodInfo>> immediatelyActivated = null;
lock (ExtensionsLock) {
foreach (var extensionMethodGroup in extensionMethodGroups) {
if (_availableExtensions == null) {
_availableExtensions = new Dictionary<string, List<IEnumerable<ExtensionMethodInfo>>>();
}
string ns = extensionMethodGroup.Key;
List<IEnumerable<ExtensionMethodInfo>> extensions;
if (_availableExtensions.TryGetValue(ns, out extensions)) {
if (extensions == null) {
if (immediatelyActivated == null) {
immediatelyActivated = new List<IEnumerable<ExtensionMethodInfo>>();
}
extensions = immediatelyActivated;
}