From e488dec40234a5806ff19da7373beb67c64e7dfc Mon Sep 17 00:00:00 2001 From: Jim Deville Date: Wed, 22 Jul 2009 11:38:40 -0700 Subject: [PATCH] syncing to head of tfs --- .../RubyRepresenter.cs | 4 +- .../Main/Hosts/IronRuby.Rack/Application.cs | 16 +- Merlin/Main/Hosts/IronRuby.Rack/RubyEngine.cs | 20 +- Merlin/Main/Hosts/IronRuby.Rack/Utils.cs | 14 +- .../DynamicEngine.cs | 6 +- .../IronPython.Modules.csproj | 6 +- .../IronPython/IronPython.Modules/_weakref.cs | 16 +- .../Compiler/ArrayGlobalAllocator.cs | 2 +- .../IronPython/Compiler/Ast/AstGenerator.cs | 15 +- .../IronPython/Compiler/OnDiskScriptCode.cs | 2 +- .../Compiler/SavableGlobalAllocator.cs | 3 +- .../Compiler/StaticGlobalAllocator.cs | 2 +- .../IronPython/Hosting/PythonCommandLine.cs | 7 + .../IronPython/IronPython.Build.csproj | Bin 55406 -> 55638 bytes .../IronPython/IronPython/IronPython.csproj | 6 +- .../IronPython/IronPython/Modules/Builtin.cs | 2 +- .../Runtime/Binding/ConversionBinder.cs | 2 +- .../Runtime/Binding/MetaOldClass.cs | 2 +- .../Runtime/Binding/MetaOldInstance.cs | 2 +- .../Runtime/Binding/MetaPythonType.Members.cs | 24 +- .../Runtime/Binding/MetaUserObject.cs | 6 +- .../Runtime/Binding/PythonBinder.cs | 77 +- .../Binding/PythonDeleteMemberBinder.cs | 2 +- .../Runtime/Binding/PythonGetMemberBinder.cs | 31 +- .../Runtime/Binding/PythonOverloadResolver.cs | 4 +- .../Binding/PythonProtocol.Operations.cs | 56 +- .../Runtime/Binding/PythonProtocol.cs | 20 +- .../Runtime/Binding/PythonSetMemberBinder.cs | 2 +- .../IronPython/IronPython/Runtime/Bytes.cs | 2 +- .../IronPython}/Runtime/CodeContext.cs | 42 +- .../IronPython/Runtime/Descriptors.cs | 2 +- .../IronPython/Runtime/Interfaces.cs | 15 + .../IronPython/IronPython/Runtime/Method.cs | 8 +- .../Runtime/Operations/PythonOps.cs | 41 +- .../IronPython/Runtime/PythonContext.cs | 14 +- .../Runtime/PythonDynamicStackFrame.cs | 38 + .../IronPython/Runtime/PythonFunction.cs | 8 +- .../Runtime/Types/BuiltinFunction.cs | 2 +- .../Runtime/Types/BuiltinMethodDescriptor.cs | 4 +- .../Runtime/Types/CustomAttributeTracker.cs | 81 +- .../IronPython/Runtime/Types/OldClass.cs | 9 +- .../IronPython/Runtime/Types/OldInstance.cs | 10 +- .../IronPython/Runtime/Types/PythonType.cs | 8 +- .../Runtime/Types/PythonTypeSlot.cs | 10 +- .../Runtime/Types/ReflectedField.cs | 6 +- .../Runtime/Types/ReflectedProperty.cs | 14 +- .../IronPython/IronPythonTest/InheritTest.cs | 2 +- .../IronPythonTest/IronPythonTest.csproj | 2 +- .../Libraries/LibraryDef.cs | 4 - .../IronRuby.Tests.VS.csproj | 60 -- .../Ruby/IronRuby.Tests/RubyTests.cs | 6 +- .../IronRuby.Tests/Runtime/DlrInteropTests.cs | 36 + .../IronRuby.Tests/Runtime/LoaderTests.cs | 36 + .../IronRuby.Tests/Runtime/RubyUtilsTests.cs | 136 ++- .../Builtins/KernelOps.cs | 12 +- .../Builtins/Marshal.cs | 5 +- .../Builtins/ModuleOps.cs | 30 +- .../Extensions/ClrNameOps.cs | 24 + .../Extensions/IEnumerableOps.cs | 4 + .../Extensions/IronRubyOps.cs | 52 +- .../Extensions/ScopeOps.cs | 41 + .../Initializers.Generated.cs | 222 +++-- .../IronRuby.Libraries.Build.csproj | Bin 20518 -> 20622 bytes .../IronRuby.Libraries.csproj | 3 +- Merlin/Main/Languages/Ruby/Ruby.sln | 34 +- .../Languages/Ruby/Ruby/Builtins/RubyClass.cs | 9 +- .../Ruby/Ruby/Builtins/RubyEncoding.cs | 2 +- .../Ruby/Ruby/Builtins/RubyModule.cs | 44 +- .../Ruby/Ruby/Compiler/Parser/Parser.cs | 2 +- .../Languages/Ruby/Ruby/Ruby.Build.csproj | Bin 44328 -> 44456 bytes Merlin/Main/Languages/Ruby/Ruby/Ruby.csproj | 3 +- .../Ruby/Runtime/Calls/ConvertToSAction.cs | 2 +- .../Ruby/Ruby/Runtime/Calls/InteropBinder.cs | 10 +- .../Ruby/Runtime/Calls/MetaObjectBuilder.cs | 30 +- .../Runtime/Calls/ProtocolConversionAction.cs | 6 +- .../Ruby/Ruby/Runtime/Calls/RubyBinder.cs | 2 +- .../Ruby/Ruby/Runtime/Calls/RubyCallAction.cs | 16 +- .../Ruby/Runtime/Calls/RubyCallSignature.cs | 14 +- .../Runtime/Calls/VisibilityContext.cs} | 27 +- .../Languages/Ruby/Ruby/Runtime/ClrName.cs | 6 +- .../Main/Languages/Ruby/Ruby/Runtime/Key.cs | 2 + .../Languages/Ruby/Ruby/Runtime/Loader.cs | 155 ++- .../Ruby/Ruby/Runtime/RubyContext.cs | 6 +- .../Languages/Ruby/Ruby/Runtime/RubyOps.cs | 4 +- .../Languages/Ruby/Ruby/Runtime/RubyScope.cs | 51 +- .../Languages/Ruby/Ruby/Runtime/RubyUtils.cs | 174 +++- .../Main/Languages/Ruby/Ruby/Runtime/Utils.cs | 32 + .../Ruby/RubyCodeCoverage.testrunconfig | 24 - .../Languages/Ruby/RubyCodeCoverage.vsmdi | 6 - .../Ruby/Samples/Tutorial/css/screen.css | 30 +- .../Samples/Tutorial/design/TutorialSL.sln | 34 +- .../Tutorial/design/TutorialSL/App.xaml | 16 +- .../Tutorial/design/TutorialSL/App.xaml.cs | 130 +-- .../design/TutorialSL/MainPage.xaml.cs | 84 +- .../TutorialSL/Properties/AppManifest.xml | 8 +- .../TutorialSL/Properties/AssemblyInfo.cs | 72 +- .../design/TutorialSL/StepControl.xaml.cs | 78 +- .../design/TutorialSL/TutorialControl.xaml | 2 +- .../design/TutorialSL/TutorialControl.xaml.cs | 78 +- .../design/TutorialSL/TutorialPage.xaml | 2 +- .../design/TutorialSL/TutorialPage.xaml.cs | 48 +- .../design/TutorialSL/TutorialSL.csproj | 212 ++-- .../Ruby/Samples/Tutorial/gui_tutorial.rb | 910 +++++++++--------- .../Ruby/Samples/Tutorial/index.html | 228 ++--- .../Ruby/Samples/Tutorial/js/error.js | 64 +- .../Ruby/Samples/Tutorial/sl_tutorial.rb | 44 +- .../Ruby/Samples/Tutorial/tutorial-sl.bat | 2 +- .../Ruby/Samples/Tutorial/tutorial.bat | 2 +- .../Languages/Ruby/Scripts/ircoverage.bat | 22 + .../net/bcl/string/construction_spec.rb | 6 +- .../Tests/Interop/net/fields/access_spec.rb | 4 +- .../net/method/invocation/generic_spec.rb | 2 +- Merlin/Main/Languages/Ruby/update-git.log | Bin 112402 -> 172424 bytes .../Actions/ActionBinder.cs | 136 +-- .../Actions/BoundMemberTracker.cs | 17 +- .../Actions/ConditionalBuilder.cs | 5 + .../Actions/DefaultBinder.Conversions.cs | 36 +- .../Actions/DefaultBinder.DeleteMember.cs | 44 +- .../Actions/DefaultBinder.GetMember.cs | 91 +- .../Actions/DefaultBinder.Operations.cs | 18 +- .../Actions/DefaultBinder.SetMember.cs | 87 +- .../Actions/DefaultBinder.cs | 39 +- .../Microsoft.Scripting/Actions/ErrorInfo.cs | 17 - .../Actions/EventTracker.cs | 18 +- .../Actions/FieldTracker.cs | 47 +- .../Actions/MemberTracker.cs | 22 +- .../Actions/MethodGroup.cs | 12 +- .../Actions/MethodTracker.cs | 57 +- .../Actions/NamespaceTracker.cs | 39 +- .../Actions/PropertyTracker.cs | 22 +- .../Actions/RuleBuilder.cs | 291 ------ .../Microsoft.Scripting/Actions/TypeGroup.cs | 2 +- .../Actions/TypeTracker.cs | 6 +- .../Ast/CodeContextExpression.cs | 109 --- .../Microsoft.Scripting/Ast/LambdaBuilder.cs | 41 +- .../Generation/CompilerHelpers.cs | 9 - .../Microsoft.Scripting.Build.csproj | Bin 49910 -> 49586 bytes .../Microsoft.Scripting.csproj | 13 +- .../Microsoft.Scripting/Runtime/BinderOps.cs | 38 - .../Runtime/DefaultLanguageContext.cs | 2 +- .../Runtime/DynamicStackFrame.cs | 10 +- .../Runtime/ExceptionHelpers.cs | 14 +- .../Runtime/IMembersList.cs | 8 +- .../Utils/ReadOnlyDictionary.cs | 4 +- .../Utils/SynchronizedDictionary.cs | 18 +- .../Scripting/Microsoft.Scripting.Core.csproj | 10 +- ...rosoft.Scripting.ExtensionAttribute.csproj | 4 +- 147 files changed, 2707 insertions(+), 2656 deletions(-) rename Merlin/Main/{Runtime/Microsoft.Scripting => Languages/IronPython/IronPython}/Runtime/CodeContext.cs (72%) create mode 100644 Merlin/Main/Languages/IronPython/IronPython/Runtime/PythonDynamicStackFrame.cs delete mode 100644 Merlin/Main/Languages/Ruby/IronRuby.Tests.VS/IronRuby.Tests.VS.csproj create mode 100644 Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/ScopeOps.cs rename Merlin/Main/Languages/Ruby/{IronRuby.Tests.VS/MsTest.cs => Ruby/Runtime/Calls/VisibilityContext.cs} (50%) delete mode 100644 Merlin/Main/Languages/Ruby/RubyCodeCoverage.testrunconfig delete mode 100644 Merlin/Main/Languages/Ruby/RubyCodeCoverage.vsmdi create mode 100644 Merlin/Main/Languages/Ruby/Scripts/ircoverage.bat delete mode 100644 Merlin/Main/Runtime/Microsoft.Scripting/Actions/RuleBuilder.cs delete mode 100644 Merlin/Main/Runtime/Microsoft.Scripting/Ast/CodeContextExpression.cs diff --git a/Merlin/External.LCA_RESTRICTED/Languages/IronRuby/Yaml/IronRuby.Libraries.Yaml/RubyRepresenter.cs b/Merlin/External.LCA_RESTRICTED/Languages/IronRuby/Yaml/IronRuby.Libraries.Yaml/RubyRepresenter.cs index 427bb32bca..688cf8e416 100644 --- a/Merlin/External.LCA_RESTRICTED/Languages/IronRuby/Yaml/IronRuby.Libraries.Yaml/RubyRepresenter.cs +++ b/Merlin/External.LCA_RESTRICTED/Languages/IronRuby/Yaml/IronRuby.Libraries.Yaml/RubyRepresenter.cs @@ -43,7 +43,7 @@ public class RubyRepresenter : Representer { public RubyRepresenter(RubyContext/*!*/ context, Serializer/*!*/ serializer, YamlOptions/*!*/ opts) : base(serializer, opts) { _context = context; - _objectToYamlMethod = context.GetClass(typeof(object)).ResolveMethod("to_yaml", RubyClass.IgnoreVisibility).Info; + _objectToYamlMethod = context.GetClass(typeof(object)).ResolveMethod("to_yaml", VisibilityContext.AllVisible).Info; _TagUri = CallSite>.Create( @@ -88,7 +88,7 @@ public RubyRepresenter(RubyContext/*!*/ context, Serializer/*!*/ serializer, Yam #endregion protected override Node CreateNode(object data) { - RubyMemberInfo method = _context.GetImmediateClassOf(data).ResolveMethodForSite("to_yaml", RubyClass.IgnoreVisibility).Info; + RubyMemberInfo method = _context.GetImmediateClassOf(data).ResolveMethodForSite("to_yaml", VisibilityContext.AllVisible).Info; if (method == _objectToYamlMethod) { return (Node)_ToYamlNode.Target(_ToYamlNode, data, this); diff --git a/Merlin/Main/Hosts/IronRuby.Rack/Application.cs b/Merlin/Main/Hosts/IronRuby.Rack/Application.cs index 594fcccb19..2a1919316d 100644 --- a/Merlin/Main/Hosts/IronRuby.Rack/Application.cs +++ b/Merlin/Main/Hosts/IronRuby.Rack/Application.cs @@ -12,7 +12,7 @@ public class Application { private readonly object _app; private readonly string _appRoot; - private readonly string _rackVersion; + private readonly string _rackVersion; private readonly string _gemPath; public object App { @@ -20,12 +20,12 @@ public class Application { } private const string AppRootOptionName = "AppRoot"; - private const string RackVersionOptionName = "RackVersion"; + private const string RackVersionOptionName = "RackVersion"; private const string GemPathOptionName = "GemPath"; public Application(HttpContext context) { _appRoot = GetRoot(context); - _rackVersion = GetRackVersion(); + _rackVersion = GetRackVersion(); _gemPath = GetGemPath(); InitRack(); @@ -41,7 +41,7 @@ public class Application { return RubyEngine.ExecuteMethod(_app, "call", envHash); } - private void InitRack() { + private void InitRack() { Environment.SetEnvironmentVariable("GEM_PATH", _gemPath); Utils.Log("=> Loading RubyGems"); @@ -83,10 +83,10 @@ public class Application { } } return root; - } - - private static string GetGemPath() { - return ConfigurationManager.AppSettings[GemPathOptionName] ?? ""; + } + + private static string GetGemPath() { + return ConfigurationManager.AppSettings[GemPathOptionName] ?? ""; } } } diff --git a/Merlin/Main/Hosts/IronRuby.Rack/RubyEngine.cs b/Merlin/Main/Hosts/IronRuby.Rack/RubyEngine.cs index 58378fcda1..f525ddc20a 100644 --- a/Merlin/Main/Hosts/IronRuby.Rack/RubyEngine.cs +++ b/Merlin/Main/Hosts/IronRuby.Rack/RubyEngine.cs @@ -41,16 +41,16 @@ public static class RubyEngine { public static object Execute(string code, ScriptScope aScope) { return Engine.CreateScriptSourceFromString(code).Execute(aScope); - } - - public static T Execute(string code) - { - return Execute(code, scope); - } - - public static T Execute(string code, ScriptScope aScope) - { - return (T)Engine.CreateScriptSourceFromString(code).Execute(aScope); + } + + public static T Execute(string code) + { + return Execute(code, scope); + } + + public static T Execute(string code, ScriptScope aScope) + { + return (T)Engine.CreateScriptSourceFromString(code).Execute(aScope); } public static T ExecuteMethod(object instance, string methodName, params object[] args) diff --git a/Merlin/Main/Hosts/IronRuby.Rack/Utils.cs b/Merlin/Main/Hosts/IronRuby.Rack/Utils.cs index 74a9110aca..9ee048c2a7 100644 --- a/Merlin/Main/Hosts/IronRuby.Rack/Utils.cs +++ b/Merlin/Main/Hosts/IronRuby.Rack/Utils.cs @@ -45,13 +45,13 @@ public class Utils { foreach (var path in RubyEngine.Engine.GetSearchPaths()) { context.Response.Write(HttpUtility.HtmlEncode(path)); context.Response.Write("\r\n"); - } - context.Response.Write("\r\n"); - context.Response.Write("

Gem paths

\r\n"); - context.Response.Write("
\r\n");
-            foreach (var gempath in RubyEngine.Execute("require 'rubygems'; Gem.path")) {
-                context.Response.Write(HttpUtility.HtmlEncode(((MutableString)gempath).ToString()));
-                context.Response.Write("\r\n");
+            }
+            context.Response.Write("
\r\n"); + context.Response.Write("

Gem paths

\r\n"); + context.Response.Write("
\r\n");
+            foreach (var gempath in RubyEngine.Execute("require 'rubygems'; Gem.path")) {
+                context.Response.Write(HttpUtility.HtmlEncode(((MutableString)gempath).ToString()));
+                context.Response.Write("\r\n");
             }
             context.Response.Write("
\r\n"); context.Response.Write("\r\n"); diff --git a/Merlin/Main/Hosts/SilverLight/Microsoft.Scripting.SilverLight/DynamicEngine.cs b/Merlin/Main/Hosts/SilverLight/Microsoft.Scripting.SilverLight/DynamicEngine.cs index 063764e82e..835825f0de 100644 --- a/Merlin/Main/Hosts/SilverLight/Microsoft.Scripting.SilverLight/DynamicEngine.cs +++ b/Merlin/Main/Hosts/SilverLight/Microsoft.Scripting.SilverLight/DynamicEngine.cs @@ -32,7 +32,7 @@ public class DynamicEngine { public ScriptScope EntryPointScope { get; private set; } public void Start() { - InitializeRuntime(Settings.Debug); + InitializeRuntime(Settings.Debug); Run(Settings.GetEntryPoint(), Settings.ConsoleEnabled); } @@ -68,8 +68,8 @@ public class DynamicEngine { private void Run(string entryPoint, bool consoleEnabled) { string code = GetEntryPointContents(); Engine = Runtime.GetEngineByFileExtension(Path.GetExtension(entryPoint)); - EntryPointScope = Engine.CreateScope(); - + EntryPointScope = Engine.CreateScope(); + if (consoleEnabled) Repl.Show(); ScriptSource sourceCode = Engine.CreateScriptSourceFromString(code, entryPoint, SourceCodeKind.File); diff --git a/Merlin/Main/Languages/IronPython/IronPython.Modules/IronPython.Modules.csproj b/Merlin/Main/Languages/IronPython/IronPython.Modules/IronPython.Modules.csproj index f340270c8e..e29c231115 100644 --- a/Merlin/Main/Languages/IronPython/IronPython.Modules/IronPython.Modules.csproj +++ b/Merlin/Main/Languages/IronPython/IronPython.Modules/IronPython.Modules.csproj @@ -19,7 +19,7 @@ true SIGNED true - ..\..\..\Utilities\Silverlight\x86ret\ + ..\..\..\Utilities\Silverlight\x86ret\ 885063680 @@ -80,8 +80,8 @@ $(SilverlightPath)\System.Core.dll systemcore - - + + diff --git a/Merlin/Main/Languages/IronPython/IronPython.Modules/_weakref.cs b/Merlin/Main/Languages/IronPython/IronPython.Modules/_weakref.cs index 3e2732132a..545a93ee99 100644 --- a/Merlin/Main/Languages/IronPython/IronPython.Modules/_weakref.cs +++ b/Merlin/Main/Languages/IronPython/IronPython.Modules/_weakref.cs @@ -251,7 +251,7 @@ public @ref(object @object) } [PythonType, DynamicBaseTypeAttribute, PythonHidden] - public sealed partial class weakproxy : IPythonObject, ICodeFormattable, IProxyObject, IValueEquality, IMembersList { + public sealed partial class weakproxy : IPythonObject, ICodeFormattable, IProxyObject, IValueEquality, IPythonMembersList { private readonly WeakHandle _target; private readonly CodeContext/*!*/ _context; @@ -406,7 +406,11 @@ public sealed partial class weakproxy : IPythonObject, ICodeFormattable, IProxyO PythonOps.DeleteAttr(context, o, SymbolTable.StringToId(name)); } - IList IMembersList.GetMemberNames(CodeContext/*!*/ context) { + IList IMembersList.GetMemberNames() { + return PythonOps.GetStringMemberList(this); + } + + IList IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { object o; if (!TryGetObject(out o)) { // if we've been disconnected return an empty list @@ -456,7 +460,7 @@ public sealed partial class weakcallableproxy : ICodeFormattable, IProxyObject, IValueEquality, - IMembersList { + IPythonMembersList { private WeakHandle _target; private readonly CodeContext/*!*/ _context; @@ -625,7 +629,11 @@ public sealed partial class weakcallableproxy : PythonOps.DeleteAttr(context, o, SymbolTable.StringToId(name)); } - IList IMembersList.GetMemberNames(CodeContext/*!*/ context) { + IList IMembersList.GetMemberNames() { + return PythonOps.GetStringMemberList(this); + } + + IList IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { object o; if (!TryGetObject(out o)) { // if we've been disconnected return an empty list diff --git a/Merlin/Main/Languages/IronPython/IronPython/Compiler/ArrayGlobalAllocator.cs b/Merlin/Main/Languages/IronPython/IronPython/Compiler/ArrayGlobalAllocator.cs index b85430c9a0..87dc1cb33a 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Compiler/ArrayGlobalAllocator.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Compiler/ArrayGlobalAllocator.cs @@ -42,7 +42,7 @@ class ArrayGlobalAllocator : GlobalAllocator { private readonly GlobalArrayConstant _array; internal static readonly MSAst.ParameterExpression/*!*/ _globalContext = Ast.Parameter(typeof(CodeContext), "$globalContext"); - public ArrayGlobalAllocator(LanguageContext/*!*/ context) { + public ArrayGlobalAllocator(PythonContext/*!*/ context) { _globalArray = Ast.Parameter(typeof(PythonGlobal[]), "$globalArray"); _scope = new Scope(new PythonDictionary(new GlobalDictionaryStorage(_globalVals))); _context = new CodeContext(_scope, context); diff --git a/Merlin/Main/Languages/IronPython/IronPython/Compiler/Ast/AstGenerator.cs b/Merlin/Main/Languages/IronPython/IronPython/Compiler/Ast/AstGenerator.cs index e542eebf58..726370e534 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Compiler/Ast/AstGenerator.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Compiler/Ast/AstGenerator.cs @@ -71,7 +71,7 @@ internal class AstGenerator { private Dictionary _handlerLocations; // list of all exception handlers and finallys. - used for debugging/tracing support to disallow jumping into handlers. Value is true if handler is finally private static readonly Dictionary _HelperMethods = new Dictionary(); // cache of helper methods - private static readonly MethodInfo _UpdateStackTrace = typeof(ExceptionHelpers).GetMethod("UpdateStackTrace"); + private static readonly MethodInfo _UpdateStackTrace = typeof(PythonOps).GetMethod("UpdateStackTrace"); private static readonly MSAst.Expression _GetCurrentMethod = Ast.Call(typeof(MethodBase).GetMethod("GetCurrentMethod")); internal static readonly MSAst.Expression[] EmptyExpression = new MSAst.Expression[0]; internal static readonly MSAst.BlockExpression EmptyBlock = Ast.Block(AstUtils.Empty()); @@ -115,16 +115,15 @@ internal AstGenerator(CompilationMode mode, CompilerContext/*!*/ context, Source _context = context; _pythonContext = (PythonContext)context.SourceUnit.LanguageContext; _document = _context.SourceUnit.Document ?? Ast.SymbolDocument(name, PyContext.LanguageGuid, PyContext.VendorGuid); - - LanguageContext pc = context.SourceUnit.LanguageContext; + switch (mode) { - case CompilationMode.Collectable: _globals = new ArrayGlobalAllocator(pc); break; + case CompilationMode.Collectable: _globals = new ArrayGlobalAllocator(_pythonContext); break; case CompilationMode.Lookup: _globals = new DictionaryGlobalAllocator(); break; - case CompilationMode.ToDisk: _globals = new SavableGlobalAllocator(pc); break; - case CompilationMode.Uncollectable: _globals = new StaticGlobalAllocator(pc, name); break; + case CompilationMode.ToDisk: _globals = new SavableGlobalAllocator(_pythonContext); break; + case CompilationMode.Uncollectable: _globals = new StaticGlobalAllocator(_pythonContext, name); break; } - PythonOptions po = (pc.Options as PythonOptions); + PythonOptions po = (_pythonContext.Options as PythonOptions); Assert.NotNull(po); if (po.EnableProfiler && mode != CompilationMode.ToDisk) { _profiler = Profiler.GetProfiler(PyContext); @@ -638,7 +637,7 @@ internal AstGenerator(CompilationMode mode, CompilerContext/*!*/ context, Source LineNumberUpdated ), Ast.Call( - typeof(ExceptionHelpers).GetMethod("UpdateStackTrace"), + _UpdateStackTrace, LocalContext, _GetCurrentMethod, AstUtils.Constant(Name), diff --git a/Merlin/Main/Languages/IronPython/IronPython/Compiler/OnDiskScriptCode.cs b/Merlin/Main/Languages/IronPython/IronPython/Compiler/OnDiskScriptCode.cs index bad40263ed..e2586d3e0e 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Compiler/OnDiskScriptCode.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Compiler/OnDiskScriptCode.cs @@ -68,7 +68,7 @@ class OnDiskScriptCode : ScriptCode { PythonGlobal[] globalArray = new PythonGlobal[optimizedCode.Names.Length]; Scope scope = new Scope(new PythonDictionary(new GlobalDictionaryStorage(globals, globalArray))); - CodeContext res = new CodeContext(scope, SourceUnit.LanguageContext); + CodeContext res = new CodeContext(scope, (PythonContext)SourceUnit.LanguageContext); for (int i = 0; i < optimizedCode.Names.Length; i++) { SymbolId name = SymbolTable.StringToId(optimizedCode.Names[i]); diff --git a/Merlin/Main/Languages/IronPython/IronPython/Compiler/SavableGlobalAllocator.cs b/Merlin/Main/Languages/IronPython/IronPython/Compiler/SavableGlobalAllocator.cs index 204ec7f9b1..9fb77ca2be 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Compiler/SavableGlobalAllocator.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Compiler/SavableGlobalAllocator.cs @@ -20,6 +20,7 @@ using Microsoft.Scripting.Ast; using Microsoft.Scripting.Runtime; +using IronPython.Runtime; using IronPython.Runtime.Operations; using MSAst = System.Linq.Expressions; @@ -30,7 +31,7 @@ namespace IronPython.Compiler.Ast { class SavableGlobalAllocator : ArrayGlobalAllocator { private readonly List/*!*/ _constants; - public SavableGlobalAllocator(LanguageContext/*!*/ context) + public SavableGlobalAllocator(PythonContext/*!*/ context) : base(context) { _constants = new List(); } diff --git a/Merlin/Main/Languages/IronPython/IronPython/Compiler/StaticGlobalAllocator.cs b/Merlin/Main/Languages/IronPython/IronPython/Compiler/StaticGlobalAllocator.cs index 8f03896480..93330af794 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Compiler/StaticGlobalAllocator.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Compiler/StaticGlobalAllocator.cs @@ -56,7 +56,7 @@ class StaticGlobalAllocator : GlobalAllocator { private StrongBox _finalType = new StrongBox(); #endif - public StaticGlobalAllocator(LanguageContext/*!*/ context, string name) { + public StaticGlobalAllocator(PythonContext/*!*/ context, string name) { _typeGen = Snippets.Shared.DefineType(name, typeof(object), false, false); _codeContextField = _typeGen.AddStaticField(typeof(CodeContext), "__global_context"); diff --git a/Merlin/Main/Languages/IronPython/IronPython/Hosting/PythonCommandLine.cs b/Merlin/Main/Languages/IronPython/IronPython/Hosting/PythonCommandLine.cs index 3dbdf8b4d2..94d43eccac 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Hosting/PythonCommandLine.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Hosting/PythonCommandLine.cs @@ -510,6 +510,13 @@ public class PythonCommandLine : CommandLine { protected override void UnhandledException(Exception e) { PythonOps.PrintException(new CodeContext(Scope, Language), e, Console); } + + private new PythonContext Language { + get { + return (PythonContext)base.Language; + } + } + } #endif } diff --git a/Merlin/Main/Languages/IronPython/IronPython/IronPython.Build.csproj b/Merlin/Main/Languages/IronPython/IronPython/IronPython.Build.csproj index 8dae91feae0a3114ee4efe6225daf1bb1c0edeeb..f8b32d5b7f625d8636bfd8d587c40f267f8285ab 100644 GIT binary patch delta 63 zcmaF2f%)1d<_#Ub%qa}1lkX=cZf^0l5|wsgsAR}vNMy)m$Ye-n2xce&vXdFI8Qd6( SCSNr2oNSOJvw2_AhEf2(eHAMJ delta 19 bcmcb%iTT|I<_#Ubn?LxPiEdt&yrC2TWrzvR diff --git a/Merlin/Main/Languages/IronPython/IronPython/IronPython.csproj b/Merlin/Main/Languages/IronPython/IronPython/IronPython.csproj index 150d76e260..8b31285041 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/IronPython.csproj +++ b/Merlin/Main/Languages/IronPython/IronPython/IronPython.csproj @@ -80,7 +80,7 @@ 1591 - + False $(SilverlightPath)\mscorlib.dll @@ -90,7 +90,7 @@ $(SilverlightPath)\System.dll - + @@ -103,6 +103,7 @@ + @@ -247,6 +248,7 @@ + diff --git a/Merlin/Main/Languages/IronPython/IronPython/Modules/Builtin.cs b/Merlin/Main/Languages/IronPython/IronPython/Modules/Builtin.cs index 834227f7a2..ada853bfb8 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Modules/Builtin.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Modules/Builtin.cs @@ -853,7 +853,7 @@ public static partial class Builtin { doc.AppendLine(); } - IList names = ((IMembersList)oldClass).GetMemberNames(context); + IList names = ((IPythonMembersList)oldClass).GetMemberNames(context); List sortNames = new List(names); sortNames.sort(context); names = sortNames; diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/ConversionBinder.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/ConversionBinder.cs index 18f6ceef3b..a689e57285 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/ConversionBinder.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/ConversionBinder.cs @@ -214,7 +214,7 @@ class PythonConversionBinder : DynamicMetaObjectBinder, IPythonSite, IExpression ); } - return res ?? EnsureReturnType(Context.Binder.ConvertTo(Type, ResultKind, self)); + return res ?? EnsureReturnType(Context.Binder.ConvertTo(Type, ResultKind, self, _context.SharedOverloadResolverFactory)); } private DynamicMetaObject EnsureReturnType(DynamicMetaObject dynamicMetaObject) { diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaOldClass.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaOldClass.cs index 0fa397e029..4bb4c15a75 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaOldClass.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaOldClass.cs @@ -98,7 +98,7 @@ public MetaOldClass(Expression/*!*/ expression, BindingRestrictions/*!*/ restric } public override System.Collections.Generic.IEnumerable GetDynamicMemberNames() { - foreach (object o in ((IMembersList)Value).GetMemberNames(DefaultContext.Default)) { + foreach (object o in ((IPythonMembersList)Value).GetMemberNames(DefaultContext.Default)) { if (o is string) { yield return (string)o; } diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaOldInstance.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaOldInstance.cs index ec477fd3e1..75d2fb9a0f 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaOldInstance.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaOldInstance.cs @@ -153,7 +153,7 @@ public MetaOldInstance(Expression/*!*/ expression, BindingRestrictions/*!*/ rest } public override System.Collections.Generic.IEnumerable GetDynamicMemberNames() { - foreach (object o in ((IMembersList)Value).GetMemberNames(DefaultContext.Default)) { + foreach (object o in ((IPythonMembersList)Value).GetMemberNames(DefaultContext.Default)) { if (o is string) { yield return (string)o; } diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaPythonType.Members.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaPythonType.Members.cs index 2aee16c966..b2e99c6424 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaPythonType.Members.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaPythonType.Members.cs @@ -86,7 +86,7 @@ partial class MetaPythonType : MetaPythonObject, IPythonGetable { tt ), value, - AstUtils.Constant(state.SharedContext) + new PythonOverloadResolverFactory(state.Binder, AstUtils.Constant(state.SharedContext)) ).Expression, Restrictions.Merge(value.Restrictions).Merge(BindingRestrictions.GetInstanceRestriction(Expression, Value)) ); @@ -112,7 +112,8 @@ partial class MetaPythonType : MetaPythonObject, IPythonGetable { AstUtils.Constant(tt), BindingRestrictions.Empty, tt - ) + ), + state.SharedOverloadResolverFactory ).Expression, BindingRestrictions.GetInstanceRestriction(Expression, Value).Merge(Restrictions) ); @@ -331,8 +332,12 @@ public MetaGetBinderHelper(MetaPythonType type, DynamicMetaObjectBinder member, pts.MakeGetExpression( _state.Binder, _codeContext, - null, - AstUtils.Convert(AstUtils.WeakConstant(Value), typeof(PythonType)), + null, + new DynamicMetaObject( + AstUtils.Convert(AstUtils.WeakConstant(Value), typeof(PythonType)), + BindingRestrictions.Empty, + Value + ), _cb ); @@ -386,10 +391,15 @@ public MetaGetBinderHelper(MetaPythonType type, DynamicMetaObjectBinder member, protected override void AddMetaSlotAccess(PythonType metaType, PythonTypeSlot pts) { ParameterExpression tmp = Ast.Variable(typeof(object), "slotRes"); - pts.MakeGetExpression(_state.Binder, + pts.MakeGetExpression( + _state.Binder, _codeContext, - Expression, - AstUtils.Constant(metaType), + _type, + new DynamicMetaObject( + AstUtils.Constant(metaType), + BindingRestrictions.Empty, + metaType + ), _cb ); diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaUserObject.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaUserObject.cs index 7823a6cc29..c6b7cdd2d3 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaUserObject.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/MetaUserObject.cs @@ -313,7 +313,7 @@ public MetaUserObject(Expression/*!*/ expression, BindingRestrictions/*!*/ restr private Expression ConversionFallback(DynamicMetaObjectBinder/*!*/ convertToAction) { PythonConversionBinder cb = convertToAction as PythonConversionBinder; if (cb != null) { - return GetConversionFailedReturnValue(cb, this); + return GetConversionFailedReturnValue(cb, this).Expression; } return convertToAction.GetUpdateExpression(typeof(object)); @@ -342,11 +342,11 @@ public MetaUserObject(Expression/*!*/ expression, BindingRestrictions/*!*/ restr /// /// Various helpers related to calling Python __*__ conversion methods /// - private Expression/*!*/ GetConversionFailedReturnValue(PythonConversionBinder/*!*/ convertToAction, DynamicMetaObject/*!*/ self) { + private DynamicMetaObject/*!*/ GetConversionFailedReturnValue(PythonConversionBinder/*!*/ convertToAction, DynamicMetaObject/*!*/ self) { switch (convertToAction.ResultKind) { case ConversionResultKind.ImplicitTry: case ConversionResultKind.ExplicitTry: - return DefaultBinder.GetTryConvertReturnValue(convertToAction.Type); + return new DynamicMetaObject(DefaultBinder.GetTryConvertReturnValue(convertToAction.Type), BindingRestrictions.Empty); case ConversionResultKind.ExplicitCast: case ConversionResultKind.ImplicitCast: DefaultBinder db = PythonContext.GetPythonContext(convertToAction).Binder; diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonBinder.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonBinder.cs index 4d1cfa9048..7b2357bd37 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonBinder.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonBinder.cs @@ -60,7 +60,7 @@ public PythonBinder(ScriptDomainManager manager, PythonContext/*!*/ pythonContex } } - public override Expression/*!*/ ConvertExpression(Expression/*!*/ expr, Type/*!*/ toType, ConversionResultKind kind, Expression context) { + public override Expression/*!*/ ConvertExpression(Expression/*!*/ expr, Type/*!*/ toType, ConversionResultKind kind, OverloadResolverFactory factory) { ContractUtils.RequiresNotNull(expr, "expr"); ContractUtils.RequiresNotNull(toType, "toType"); @@ -85,7 +85,7 @@ public PythonBinder(ScriptDomainManager manager, PythonContext/*!*/ pythonContex } return Binders.Convert( - context, + ((PythonOverloadResolverFactory)factory)._codeContext, _context, visType, visType == typeof(char) ? ConversionResultKind.ImplicitCast : kind, @@ -182,9 +182,9 @@ public PythonBinder(ScriptDomainManager manager, PythonContext/*!*/ pythonContex ); } - public override ErrorInfo/*!*/ MakeNonPublicMemberGetError(Expression codeContext, MemberTracker member, Type type, Expression instance) { + public override ErrorInfo/*!*/ MakeNonPublicMemberGetError(OverloadResolverFactory resolverFactory, MemberTracker member, Type type, DynamicMetaObject instance) { if (PrivateBinding) { - return base.MakeNonPublicMemberGetError(codeContext, member, type, instance); + return base.MakeNonPublicMemberGetError(resolverFactory, member, type, instance); } return ErrorInfo.FromValue( @@ -192,11 +192,11 @@ public PythonBinder(ScriptDomainManager manager, PythonContext/*!*/ pythonContex ); } - public override ErrorInfo/*!*/ MakeStaticAssignFromDerivedTypeError(Type accessingType, DynamicMetaObject instance, MemberTracker info, Expression assignedValue, Expression context) { + public override ErrorInfo/*!*/ MakeStaticAssignFromDerivedTypeError(Type accessingType, DynamicMetaObject instance, MemberTracker info, DynamicMetaObject assignedValue, OverloadResolverFactory factory) { return MakeMissingMemberError(accessingType, instance, info.Name); } - public override ErrorInfo/*!*/ MakeStaticPropertyInstanceAccessError(PropertyTracker/*!*/ tracker, bool isAssignment, IList/*!*/ parameters) { + public override ErrorInfo/*!*/ MakeStaticPropertyInstanceAccessError(PropertyTracker/*!*/ tracker, bool isAssignment, IList/*!*/ parameters) { ContractUtils.RequiresNotNull(tracker, "tracker"); ContractUtils.RequiresNotNull(parameters, "parameters"); @@ -240,36 +240,18 @@ public PythonBinder(ScriptDomainManager manager, PythonContext/*!*/ pythonContex } - public override ErrorInfo/*!*/ MakeEventValidation(MemberGroup/*!*/ members, Expression eventObject, Expression/*!*/ value, Expression/*!*/ codeContext) { + public override ErrorInfo/*!*/ MakeEventValidation(MemberGroup/*!*/ members, DynamicMetaObject eventObject, DynamicMetaObject/*!*/ value, OverloadResolverFactory/*!*/ factory) { EventTracker ev = (EventTracker)members[0]; return ErrorInfo.FromValueNoError( Ast.Block( Ast.Call( typeof(PythonOps).GetMethod("SlotTrySetValue"), - codeContext, + ((PythonOverloadResolverFactory)factory)._codeContext, AstUtils.Constant(PythonTypeOps.GetReflectedEvent(ev)), - eventObject != null ? AstUtils.Convert(eventObject, typeof(object)) : AstUtils.Constant(null), + eventObject != null ? AstUtils.Convert(eventObject.Expression, typeof(object)) : AstUtils.Constant(null), AstUtils.Constant(null, typeof(PythonType)), - AstUtils.Convert(value, typeof(object)) - ), - Ast.Constant(null) - ) - ); - } - - public override ErrorInfo MakeEventValidation(RuleBuilder rule, MemberGroup members) { - EventTracker ev = (EventTracker)members[0]; - - return ErrorInfo.FromValueNoError( - Ast.Block( - Ast.Call( - typeof(PythonOps).GetMethod("SlotTrySetValue"), - rule.Context, - AstUtils.Constant(PythonTypeOps.GetReflectedEvent(ev)), - AstUtils.Convert(rule.Parameters[0], typeof(object)), - AstUtils.Constant(null, typeof(PythonType)), - AstUtils.Convert(rule.Parameters[1], typeof(object)) + AstUtils.Convert(value.Expression, typeof(object)) ), Ast.Constant(null) ) @@ -408,33 +390,33 @@ public PythonBinder(ScriptDomainManager manager, PythonContext/*!*/ pythonContex return _dlrExtensionTypes.ContainsKey(t); } - public override Expression ReturnMemberTracker(Type type, MemberTracker memberTracker) { - Expression res = ReturnMemberTracker(type, memberTracker, PrivateBinding); + public override DynamicMetaObject ReturnMemberTracker(Type type, MemberTracker memberTracker) { + var res = ReturnMemberTracker(type, memberTracker, PrivateBinding); return res ?? base.ReturnMemberTracker(type, memberTracker); } - private static Expression ReturnMemberTracker(Type type, MemberTracker memberTracker, bool privateBinding) { + private static DynamicMetaObject ReturnMemberTracker(Type type, MemberTracker memberTracker, bool privateBinding) { switch (memberTracker.MemberType) { case TrackerTypes.TypeGroup: - return AstUtils.Constant(memberTracker); + return new DynamicMetaObject(AstUtils.Constant(memberTracker), BindingRestrictions.Empty, memberTracker); case TrackerTypes.Type: return ReturnTypeTracker((TypeTracker)memberTracker); case TrackerTypes.Bound: - return ReturnBoundTracker((BoundMemberTracker)memberTracker, privateBinding); + return new DynamicMetaObject(ReturnBoundTracker((BoundMemberTracker)memberTracker, privateBinding), BindingRestrictions.Empty); case TrackerTypes.Property: - return ReturnPropertyTracker((PropertyTracker)memberTracker, privateBinding); + return new DynamicMetaObject(ReturnPropertyTracker((PropertyTracker)memberTracker, privateBinding), BindingRestrictions.Empty);; case TrackerTypes.Event: - return Ast.Call( + return new DynamicMetaObject(Ast.Call( typeof(PythonOps).GetMethod("MakeBoundEvent"), AstUtils.Constant(PythonTypeOps.GetReflectedEvent((EventTracker)memberTracker)), AstUtils.Constant(null), AstUtils.Constant(type) - ); + ), BindingRestrictions.Empty);; case TrackerTypes.Field: - return ReturnFieldTracker((FieldTracker)memberTracker); + return new DynamicMetaObject(ReturnFieldTracker((FieldTracker)memberTracker), BindingRestrictions.Empty);; case TrackerTypes.MethodGroup: - return ReturnMethodGroup((MethodGroup)memberTracker); + return new DynamicMetaObject(ReturnMethodGroup((MethodGroup)memberTracker), BindingRestrictions.Empty); ; case TrackerTypes.Constructor: MethodBase[] ctors = CompilerHelpers.GetConstructors(type, privateBinding, true); object val; @@ -448,9 +430,13 @@ public PythonBinder(ScriptDomainManager manager, PythonContext/*!*/ pythonContex val = PythonTypeOps.GetConstructor(type, InstanceOps.NonDefaultNewInst, ctors); } - return AstUtils.Constant(val); + return new DynamicMetaObject(AstUtils.Constant(val), BindingRestrictions.Empty, val); case TrackerTypes.Custom: - return AstUtils.Constant(((PythonCustomTracker)memberTracker).GetSlot(), typeof(PythonTypeSlot)); + return new DynamicMetaObject( + AstUtils.Constant(((PythonCustomTracker)memberTracker).GetSlot(), typeof(PythonTypeSlot)), + BindingRestrictions.Empty, + ((PythonCustomTracker)memberTracker).GetSlot() + ); } return null; } @@ -621,13 +607,13 @@ public PythonBinder(ScriptDomainManager manager, PythonContext/*!*/ pythonContex return Ast.New( typeof(ReflectedIndexer).GetConstructor(new Type[] { typeof(ReflectedIndexer), typeof(object) }), AstUtils.Constant(new ReflectedIndexer(((ReflectedPropertyTracker)pt).Property, NameType.Property, privateBinding)), - boundMemberTracker.Instance + boundMemberTracker.Instance.Expression ); case TrackerTypes.Event: return Ast.Call( typeof(PythonOps).GetMethod("MakeBoundEvent"), AstUtils.Constant(PythonTypeOps.GetReflectedEvent((EventTracker)boundMemberTracker.BoundTo)), - boundMemberTracker.Instance, + boundMemberTracker.Instance.Expression, AstUtils.Constant(boundMemberTracker.DeclaringType) ); case TrackerTypes.MethodGroup: @@ -635,7 +621,7 @@ public PythonBinder(ScriptDomainManager manager, PythonContext/*!*/ pythonContex typeof(PythonOps).GetMethod("MakeBoundBuiltinFunction"), AstUtils.Constant(GetBuiltinFunction((MethodGroup)boundTo)), AstUtils.Convert( - boundMemberTracker.Instance, + boundMemberTracker.Instance.Expression, typeof(object) ) ); @@ -662,9 +648,10 @@ public PythonBinder(ScriptDomainManager manager, PythonContext/*!*/ pythonContex return AstUtils.Constant(PythonTypeOps.GetReflectedProperty(propertyTracker, null, privateBinding)); } - private static Expression ReturnTypeTracker(TypeTracker memberTracker) { + private static DynamicMetaObject ReturnTypeTracker(TypeTracker memberTracker) { // all non-group types get exposed as PythonType's - return AstUtils.Constant(DynamicHelpers.GetPythonTypeFromType(memberTracker.Type)); + object value = DynamicHelpers.GetPythonTypeFromType(memberTracker.Type); + return new DynamicMetaObject(Ast.Constant(value), BindingRestrictions.Empty, value); } internal ScriptDomainManager/*!*/ DomainManager { diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonDeleteMemberBinder.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonDeleteMemberBinder.cs index d8992e130b..5507308e82 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonDeleteMemberBinder.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonDeleteMemberBinder.cs @@ -45,7 +45,7 @@ public PythonDeleteMemberBinder(PythonContext/*!*/ context, string/*!*/ name, bo return Defer(self); } - return Context.Binder.DeleteMember(Name, self, AstUtils.Constant(Context.SharedContext)); + return Context.Binder.DeleteMember(Name, self, new PythonOverloadResolverFactory(_context.Binder, AstUtils.Constant(Context.SharedContext))); } public PythonContext/*!*/ Context { diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonGetMemberBinder.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonGetMemberBinder.cs index 23a7a08331..217234673e 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonGetMemberBinder.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonGetMemberBinder.cs @@ -520,13 +520,14 @@ class NamespaceTrackerDelegate : FastGetBase { public DynamicMetaObject/*!*/ Fallback(DynamicMetaObject/*!*/ self, DynamicMetaObject/*!*/ codeContext) { // Python always provides an extra arg to GetMember to flow the context. - return FallbackWorker(self, codeContext, Name, _options, this, null); + return FallbackWorker(_context, self, codeContext, Name, _options, this, null); } - internal static DynamicMetaObject FallbackWorker(DynamicMetaObject/*!*/ self, DynamicMetaObject/*!*/ codeContext, string name, GetMemberOptions options, DynamicMetaObjectBinder action, DynamicMetaObject errorSuggestion) { + internal static DynamicMetaObject FallbackWorker(PythonContext context, DynamicMetaObject/*!*/ self, DynamicMetaObject/*!*/ codeContext, string name, GetMemberOptions options, DynamicMetaObjectBinder action, DynamicMetaObject errorSuggestion) { if (self.NeedsDeferral()) { return action.Defer(self); } + PythonOverloadResolverFactory resolverFactory = new PythonOverloadResolverFactory(context.Binder, codeContext.Expression); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "FallbackGet"); @@ -544,7 +545,7 @@ class NamespaceTrackerDelegate : FastGetBase { DynamicMetaObject baseRes = PythonContext.GetPythonContext(action).Binder.GetMember( name, self, - codeContext.Expression, + resolverFactory, isNoThrow, errorSuggestion ); @@ -581,11 +582,11 @@ class NamespaceTrackerDelegate : FastGetBase { } } - var res = PythonContext.GetPythonContext(action).Binder.GetMember(name, self, codeContext.Expression, isNoThrow, errorSuggestion); + var res = PythonContext.GetPythonContext(action).Binder.GetMember(name, self, resolverFactory, isNoThrow, errorSuggestion); // Default binder can return something typed to boolean or int. // If that happens, we need to apply Python's boxing rules. - if (res.Expression.Type == typeof(bool) || res.Expression.Type == typeof(int)) { + if (res.Expression.Type.IsValueType) { res = new DynamicMetaObject( AstUtils.Convert(res.Expression, typeof(object)), res.Restrictions @@ -605,7 +606,7 @@ class NamespaceTrackerDelegate : FastGetBase { name ), typeof(object) - ); + ).Expression; } public string Name { @@ -660,16 +661,16 @@ class NamespaceTrackerDelegate : FastGetBase { } class CompatibilityGetMember : GetMemberBinder, IPythonSite { - private readonly PythonContext/*!*/ _state; + private readonly PythonContext/*!*/ _context; - public CompatibilityGetMember(PythonContext/*!*/ binder, string/*!*/ name) + public CompatibilityGetMember(PythonContext/*!*/ context, string/*!*/ name) : base(name, false) { - _state = binder; + _context = context; } - public CompatibilityGetMember(PythonContext/*!*/ binder, string/*!*/ name, bool ignoreCase) + public CompatibilityGetMember(PythonContext/*!*/ context, string/*!*/ name, bool ignoreCase) : base(name, ignoreCase) { - _state = binder; + _context = context; } public override DynamicMetaObject FallbackGetMember(DynamicMetaObject self, DynamicMetaObject errorSuggestion) { @@ -679,19 +680,19 @@ public CompatibilityGetMember(PythonContext/*!*/ binder, string/*!*/ name, bool return com; } #endif - return PythonGetMemberBinder.FallbackWorker(self, PythonContext.GetCodeContextMOCls(this), Name, GetMemberOptions.None, this, errorSuggestion); + return PythonGetMemberBinder.FallbackWorker(_context, self, PythonContext.GetCodeContextMOCls(this), Name, GetMemberOptions.None, this, errorSuggestion); } #region IPythonSite Members public PythonContext Context { - get { return _state; } + get { return _context; } } #endregion public override int GetHashCode() { - return base.GetHashCode() ^ _state.Binder.GetHashCode(); + return base.GetHashCode() ^ _context.Binder.GetHashCode(); } public override bool Equals(object obj) { @@ -700,7 +701,7 @@ public CompatibilityGetMember(PythonContext/*!*/ binder, string/*!*/ name, bool return false; } - return ob._state.Binder == _state.Binder && + return ob._context.Binder == _context.Binder && base.Equals(obj); } } diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonOverloadResolver.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonOverloadResolver.cs index c07c6c4ea0..9d961b2cd4 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonOverloadResolver.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonOverloadResolver.cs @@ -29,7 +29,7 @@ namespace IronPython.Runtime.Binding { internal sealed class PythonOverloadResolverFactory : OverloadResolverFactory { private readonly PythonBinder/*!*/ _binder; - private readonly Expression/*!*/ _codeContext; + internal readonly Expression/*!*/ _codeContext; public PythonOverloadResolverFactory(PythonBinder/*!*/ binder, Expression/*!*/ codeContext) { Assert.NotNull(binder, codeContext); @@ -137,7 +137,7 @@ public PythonOverloadResolver(PythonBinder binder, IList args } public override Expression Convert(DynamicMetaObject metaObject, Type restrictedType, ParameterInfo info, Type toType) { - return Binder.ConvertExpression(metaObject.Expression, toType, ConversionResultKind.ExplicitCast, _context); + return Binder.ConvertExpression(metaObject.Expression, toType, ConversionResultKind.ExplicitCast, new PythonOverloadResolverFactory(Binder, _context)); } public override Expression GetDynamicConversion(Expression value, Type type) { diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonProtocol.Operations.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonProtocol.Operations.cs index fd247f6136..4759184c32 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonProtocol.Operations.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonProtocol.Operations.cs @@ -637,50 +637,6 @@ static partial class PythonProtocol { ); } - private static DynamicMetaObject/*!*/ MakeMemberNamesOperation(PythonOperationBinder/*!*/ operation, DynamicMetaObject[] args) { - DynamicMetaObject self = args[0]; - CodeContext context; - if (args.Length > 1 && args[0].GetLimitType() == typeof(CodeContext)) { - self = args[1]; - context = (CodeContext)args[0].Value; - } else { - context = PythonContext.GetPythonContext(operation).SharedContext; - } - - if (typeof(IMembersList).IsAssignableFrom(self.GetLimitType())) { - return MakeIMembersListRule(PythonContext.GetCodeContext(operation), self); - } - - PythonType pt = DynamicHelpers.GetPythonType(self.Value); - List strNames = GetMemberNames(context, pt, self.Value); - - if (pt.IsSystemType) { - return new DynamicMetaObject( - AstUtils.Constant(strNames), - BindingRestrictions.GetInstanceRestriction(self.Expression, self.Value).Merge(self.Restrictions) - ); - } - - return new DynamicMetaObject( - AstUtils.Constant(strNames), - BindingRestrictions.GetInstanceRestriction(self.Expression, self.Value).Merge(self.Restrictions) - ); - } - - private static DynamicMetaObject MakeIMembersListRule(Expression codeContext, DynamicMetaObject target) { - return new DynamicMetaObject( - Ast.Call( - typeof(BinderOps).GetMethod("GetStringMembers"), - Ast.Call( - AstUtils.Convert(target.Expression, typeof(IMembersList)), - typeof(IMembersList).GetMethod("GetMemberNames"), - codeContext - ) - ), - BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target.Expression, target.GetLimitType()).Merge(target.Restrictions) - ); - } - internal static DynamicMetaObject/*!*/ MakeCallSignatureOperation(DynamicMetaObject/*!*/ self, IList/*!*/ targets) { List arrres = new List(); foreach (MethodBase mb in targets) { @@ -1783,10 +1739,14 @@ public SlotCallable(PythonContext/*!*/ binder, PythonIndexType op, PythonTypeSlo _slot.MakeGetExpression( Binder, AstUtils.Constant(PythonContext.SharedContext), - args[0].Expression, - Ast.Call( - typeof(DynamicHelpers).GetMethod("GetPythonType"), - AstUtils.Convert(args[0].Expression, typeof(object)) + args[0], + new DynamicMetaObject( + Ast.Call( + typeof(DynamicHelpers).GetMethod("GetPythonType"), + AstUtils.Convert(args[0].Expression, typeof(object)) + ), + BindingRestrictions.Empty, + DynamicHelpers.GetPythonType(args[0].Value) ), cb ); diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonProtocol.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonProtocol.cs index 77ee4bc52f..198efe9613 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonProtocol.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonProtocol.cs @@ -145,7 +145,7 @@ static partial class PythonProtocol { callSlot.MakeGetExpression( pyContext.Binder, PythonContext.GetCodeContext(call), - self.Expression, + self, GetPythonType(self), cb ); @@ -187,17 +187,25 @@ static partial class PythonProtocol { return null; } - private static Expression/*!*/ GetPythonType(DynamicMetaObject/*!*/ self) { + private static DynamicMetaObject/*!*/ GetPythonType(DynamicMetaObject/*!*/ self) { Assert.NotNull(self); PythonType pt = DynamicHelpers.GetPythonType(self.Value); if (pt.IsSystemType) { - return AstUtils.Constant(pt); + return new DynamicMetaObject( + AstUtils.Constant(pt), + BindingRestrictions.Empty, + pt + ); } - return Ast.Property( - Ast.Convert(self.Expression, typeof(IPythonObject)), - TypeInfo._IPythonObject.PythonType + return new DynamicMetaObject( + Ast.Property( + Ast.Convert(self.Expression, typeof(IPythonObject)), + TypeInfo._IPythonObject.PythonType + ), + BindingRestrictions.Empty, + pt ); } diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonSetMemberBinder.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonSetMemberBinder.cs index 3e8d106a9d..4afe25b1c9 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonSetMemberBinder.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Binding/PythonSetMemberBinder.cs @@ -51,7 +51,7 @@ public PythonSetMemberBinder(PythonContext/*!*/ context, string/*!*/ name, bool return com; } #endif - return Context.Binder.SetMember(Name, self, value, AstUtils.Constant(Context.SharedContext)); + return Context.Binder.SetMember(Name, self, value, new PythonOverloadResolverFactory(_context.Binder, AstUtils.Constant(Context.SharedContext))); } public override T BindDelegate(CallSite site, object[] args) { diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Bytes.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Bytes.cs index 00bfc8f33f..d96191adb2 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Bytes.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Bytes.cs @@ -659,7 +659,7 @@ public class Bytes : IList, ICodeFormattable, IExpressionSerializable { ); } - public virtual string/*!*/ __repr__(Microsoft.Scripting.Runtime.CodeContext context) { + public virtual string/*!*/ __repr__(CodeContext context) { return _bytes.BytesRepr(); } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/CodeContext.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/CodeContext.cs similarity index 72% rename from Merlin/Main/Runtime/Microsoft.Scripting/Runtime/CodeContext.cs rename to Merlin/Main/Languages/IronPython/IronPython/Runtime/CodeContext.cs index ec27f953f3..bb53512e5c 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/CodeContext.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/CodeContext.cs @@ -15,56 +15,50 @@ using System.Diagnostics; using Microsoft.Scripting.Utils; +using Microsoft.Scripting.Runtime; -namespace Microsoft.Scripting.Runtime { +namespace IronPython.Runtime { /// - /// TODO: Rename to LocalScope + /// Captures the state of a piece of code. /// - public class CodeContext { - public const string ContextFieldName = "__global_context"; - - // TODO: move to subclasses + public sealed class CodeContext { private readonly Scope _scope; + private readonly PythonContext _languageContext; + private readonly CodeContext _parent; - // TODO: move to subclasses - private readonly LanguageContext _languageContext; + public CodeContext(Scope scope, PythonContext languageContext) + : this(scope, languageContext, null) { + } - private readonly CodeContext _parent; + public CodeContext(Scope scope, PythonContext languageContext, CodeContext parent) { + Assert.NotNull(languageContext); + + _languageContext = languageContext; + _scope = scope; + _parent = parent; + } public CodeContext Parent { get { return _parent; } } - // TODO: remove public Scope Scope { get { return _scope; } } - public virtual Scope GlobalScope { + public Scope GlobalScope { get { Debug.Assert(_scope != null, "Global scope not available"); return _scope.ModuleScope; } } - public LanguageContext LanguageContext { + public PythonContext LanguageContext { get { return _languageContext; } } - - public CodeContext(Scope scope, LanguageContext languageContext) - : this(scope, languageContext, null) { - } - - public CodeContext(Scope scope, LanguageContext languageContext, CodeContext parent) { - Assert.NotNull(languageContext); - - _languageContext = languageContext; - _scope = scope; - _parent = parent; - } } } diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Descriptors.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Descriptors.cs index a365641472..76811151d9 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Descriptors.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Descriptors.cs @@ -149,7 +149,7 @@ public class PythonProperty : PythonTypeDataSlot { } [SpecialName, PropertyMethod, WrapperDescriptor] - public static void Set__doc__(PythonProperty self) { + public static void Set__doc__(PythonProperty self, object value) { throw PythonOps.TypeError("'property' object is immutable"); } diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Interfaces.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Interfaces.cs index da554d55db..ed29a0c398 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Interfaces.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Interfaces.cs @@ -13,6 +13,7 @@ * * ***************************************************************************/ +using System.Collections.Generic; using Microsoft.Scripting.Runtime; namespace IronPython.Runtime { @@ -53,4 +54,18 @@ public interface IWeakReferenceable { public interface IProxyObject { object Target { get; } } + + /// + /// Provides a list of all the members of an instance. ie. all the keys in the + /// dictionary of the object. Note that it can contain objects that are not strings. + /// + /// Such keys can be added in IronPython using syntax like: + /// obj.__dict__[100] = someOtherObject + /// + /// This Python specific version also supports filtering based upon the show cls + /// flag by flowing in the code context. + /// + public interface IPythonMembersList : IMembersList { + IList GetMemberNames(CodeContext context); + } } \ No newline at end of file diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Method.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Method.cs index a03a721c11..e05eba7ec3 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Method.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Method.cs @@ -28,7 +28,7 @@ namespace IronPython.Runtime { [PythonType("instancemethod"), DontMapGetMemberNamesToDir] - public sealed partial class Method : PythonTypeSlot, IWeakReferenceable, IMembersList, IDynamicMetaObjectProvider, ICodeFormattable { + public sealed partial class Method : PythonTypeSlot, IWeakReferenceable, IPythonMembersList, IDynamicMetaObjectProvider, ICodeFormattable { private readonly object _func; private readonly object _inst; private readonly object _declaringClass; @@ -204,7 +204,11 @@ public sealed partial class Method : PythonTypeSlot, IWeakReferenceable, IMember TypeCache.Method.DeleteMember(context, this, SymbolTable.StringToId(name)); } - IList IMembersList.GetMemberNames(CodeContext context) { + IList IMembersList.GetMemberNames() { + return PythonOps.GetStringMemberList(this); + } + + IList IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { List ret = TypeCache.Method.GetMemberNames(context); ret.AddNoLockNoDups(SymbolTable.IdToString(Symbols.Module)); diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Operations/PythonOps.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Operations/PythonOps.cs index 087067a57a..053b9fa5c5 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Operations/PythonOps.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Operations/PythonOps.cs @@ -1006,10 +1006,25 @@ public static partial class PythonOps { throw PythonOps.AttributeErrorForMissingAttribute(PythonTypeOps.GetName(o), name); } + internal static IList GetStringMemberList(IPythonMembersList pyMemList) { + List res = new List(); + foreach (object o in pyMemList.GetMemberNames(DefaultContext.Default)) { + if (o is string) { + res.Add((string)o); + } + } + return res; + } + public static IList GetAttrNames(CodeContext/*!*/ context, object o) { + IPythonMembersList pyMemList = o as IPythonMembersList; + if (pyMemList != null) { + return pyMemList.GetMemberNames(context); + } + IMembersList memList = o as IMembersList; if (memList != null) { - return memList.GetMemberNames(context); + return new List(memList.GetMemberNames()); } IPythonObject po = o as IPythonObject; @@ -2004,8 +2019,12 @@ public static partial class PythonOps { // dynamic method, strip the trailing id... name = name.Substring(0, name.IndexOf('#')); } - CodeContext context = frame.CodeContext; - if (context == null) { + + PythonDynamicStackFrame pyFrame = frame as PythonDynamicStackFrame; + CodeContext context; + if (pyFrame != null) { + context = pyFrame.CodeContext; + } else { context = DefaultContext.Default; } @@ -3657,7 +3676,7 @@ public static partial class PythonOps { } public static CodeContext/*!*/ CreateTopLevelCodeContext(Scope/*!*/ scope, LanguageContext/*!*/ context) { context.EnsureScopeExtension(scope.ModuleScope); - return new CodeContext(scope, context); + return new CodeContext(scope, (PythonContext)context); } public static PythonGlobal/*!*/[]/*!*/ GetGlobalArray(Scope/*!*/ scope) { @@ -4062,6 +4081,20 @@ public static partial class PythonOps { code.Parameters ); } + + public static void UpdateStackTrace(CodeContext context, MethodBase method, string funcName, string filename, int line) { + if (line != -1) { + Debug.Assert(filename != null); + if (ExceptionHelpers.DynamicStackFrames == null) { + ExceptionHelpers.DynamicStackFrames = new List(); + } + + Debug.Assert(line != SourceLocation.None.Line); + + ExceptionHelpers.DynamicStackFrames.Add(new PythonDynamicStackFrame(context, method, funcName, filename, line)); + } + } + } public struct FunctionStack { diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/PythonContext.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/PythonContext.cs index cf0fa90cc0..476cb6ec7e 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/PythonContext.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/PythonContext.cs @@ -61,6 +61,7 @@ public sealed class PythonContext : LanguageContext { private readonly PythonOptions/*!*/ _options; private readonly Scope/*!*/ _systemState; private readonly Dictionary/*!*/ _builtinsDict; + private readonly PythonOverloadResolverFactory _sharedOverloadResolverFactory; #if !SILVERLIGHT private readonly AssemblyResolveHolder _resolveHolder; #endif @@ -190,6 +191,7 @@ public PythonContext(ScriptDomainManager/*!*/ manager, IDictionary + /// Returns an overload resolver for the current PythonContext. The overload + /// resolver will flow the shared context through as it's CodeContext. + /// + internal PythonOverloadResolverFactory SharedOverloadResolverFactory { + get { + return _sharedOverloadResolverFactory; + } + } + /// /// Returns a shared code context for the current PythonContext. This shared /// context can be used for doing lookups which need to occur as if they diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/PythonDynamicStackFrame.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/PythonDynamicStackFrame.cs new file mode 100644 index 0000000000..ec215c3c56 --- /dev/null +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/PythonDynamicStackFrame.cs @@ -0,0 +1,38 @@ +/* **************************************************************************** + * + * Copyright (c) Microsoft Corporation. + * + * This source code is subject to terms and conditions of the Microsoft Public License. A + * copy of the license can be found in the License.html file at the root of this distribution. If + * you cannot locate the Microsoft Public License, please send an email to + * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound + * by the terms of the Microsoft Public License. + * + * You must not remove this notice, or any other, from this software. + * + * + * ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.Scripting.Runtime; +using System.Reflection; + +namespace IronPython.Runtime { + class PythonDynamicStackFrame : DynamicStackFrame { + private CodeContext _context; + + public PythonDynamicStackFrame(CodeContext context, MethodBase method, string funcName, string filename, int line) + : base(method, funcName, filename, line) { + _context = context; + } + + public CodeContext CodeContext { + get { + return _context; + } + } + + } +} diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/PythonFunction.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/PythonFunction.cs index c272fd4b55..092c19dac0 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/PythonFunction.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/PythonFunction.cs @@ -39,7 +39,7 @@ namespace IronPython.Runtime { /// Created for a user-defined function. /// [PythonType("function"), DontMapGetMemberNamesToDir] - public sealed partial class PythonFunction : PythonTypeSlot, IWeakReferenceable, IMembersList, IDynamicMetaObjectProvider, ICodeFormattable, Binding.IFastInvokable { + public sealed partial class PythonFunction : PythonTypeSlot, IWeakReferenceable, IPythonMembersList, IDynamicMetaObjectProvider, ICodeFormattable, Binding.IFastInvokable { private readonly CodeContext/*!*/ _context; // the creating code context of the function [PythonHidden] public readonly MutableTuple Closure; @@ -440,7 +440,11 @@ public sealed partial class PythonFunction : PythonTypeSlot, IWeakReferenceable, return _dict.Remove(SymbolTable.StringToId(name)); } - IList IMembersList.GetMemberNames(CodeContext context) { + IList IMembersList.GetMemberNames() { + return PythonOps.GetStringMemberList(this); + } + + IList IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { List list; if (_dict == null) { list = PythonOps.MakeList(); diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/BuiltinFunction.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/BuiltinFunction.cs index cf8dfed08a..f249defcb8 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/BuiltinFunction.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/BuiltinFunction.cs @@ -329,7 +329,7 @@ public partial class BuiltinFunction : PythonTypeSlot, ICodeFormattable, IDynami } } - internal override void MakeGetExpression(PythonBinder/*!*/ binder, Expression/*!*/ codeContext, Expression instance, Expression/*!*/ owner, ConditionalBuilder/*!*/ builder) { + internal override void MakeGetExpression(PythonBinder/*!*/ binder, Expression/*!*/ codeContext, DynamicMetaObject instance, DynamicMetaObject/*!*/ owner, ConditionalBuilder/*!*/ builder) { builder.FinishCondition(Ast.Constant(this)); } diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/BuiltinMethodDescriptor.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/BuiltinMethodDescriptor.cs index 9bbff313f5..71014cf056 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/BuiltinMethodDescriptor.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/BuiltinMethodDescriptor.cs @@ -51,13 +51,13 @@ public sealed class BuiltinMethodDescriptor : PythonTypeSlot, IDynamicMetaObject return true; } - internal override void MakeGetExpression(PythonBinder/*!*/ binder, Expression/*!*/ codeContext, Expression instance, Expression/*!*/ owner, ConditionalBuilder/*!*/ builder) { + internal override void MakeGetExpression(PythonBinder/*!*/ binder, Expression/*!*/ codeContext, DynamicMetaObject instance, DynamicMetaObject/*!*/ owner, ConditionalBuilder/*!*/ builder) { if (instance != null) { builder.FinishCondition( Ast.Call( typeof(PythonOps).GetMethod("MakeBoundBuiltinFunction"), AstUtils.Constant(_template), - instance + instance.Expression ) ); } else { diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/CustomAttributeTracker.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/CustomAttributeTracker.cs index 0530847513..0dff7eda64 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/CustomAttributeTracker.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/CustomAttributeTracker.cs @@ -16,11 +16,16 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Linq.Expressions; +using System.Dynamic; using System.Reflection; -using IronPython.Runtime.Operations; + using Microsoft.Scripting; using Microsoft.Scripting.Actions; +using Microsoft.Scripting.Actions.Calls; + +using IronPython.Runtime.Binding; +using IronPython.Runtime.Operations; + using Ast = System.Linq.Expressions.Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; @@ -28,52 +33,48 @@ namespace IronPython.Runtime.Types { public abstract class PythonCustomTracker : CustomTracker { public abstract PythonTypeSlot/*!*/ GetSlot(); - public override Expression GetValue(Expression context, ActionBinder binder, Type type) { - return AstUtils.Constant(GetSlot(), typeof(PythonTypeSlot)); + public override DynamicMetaObject GetValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type) { + return new DynamicMetaObject(AstUtils.Constant(GetSlot(), typeof(PythonTypeSlot)), BindingRestrictions.Empty); } - public override MemberTracker BindToInstance(Expression instance) { + public override MemberTracker BindToInstance(DynamicMetaObject instance) { return new BoundMemberTracker(this, instance); } - public override Expression SetValue(Expression context, ActionBinder binder, Type type, Expression value) { - return SetBoundValue(context, binder, type, value, AstUtils.Constant(null)); + public override DynamicMetaObject SetValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type, DynamicMetaObject value) { + return SetBoundValue(resolverFactory, binder, type, value, new DynamicMetaObject(AstUtils.Constant(null), BindingRestrictions.Empty)); } - protected override Expression GetBoundValue(Expression context, ActionBinder binder, Type type, Expression instance) { - return Ast.Call( - typeof(PythonOps).GetMethod("SlotGetValue"), - context, - AstUtils.Constant(GetSlot(), typeof(PythonTypeSlot)), - AstUtils.Convert( - instance, - typeof(object) + protected override DynamicMetaObject GetBoundValue(OverloadResolverFactory factory, ActionBinder binder, Type type, DynamicMetaObject instance) { + return new DynamicMetaObject( + Ast.Call( + typeof(PythonOps).GetMethod("SlotGetValue"), + ((PythonOverloadResolverFactory)factory)._codeContext, + AstUtils.Constant(GetSlot(), typeof(PythonTypeSlot)), + AstUtils.Convert( + instance.Expression, + typeof(object) + ), + AstUtils.Constant(DynamicHelpers.GetPythonTypeFromType(type)) ), - AstUtils.Constant(DynamicHelpers.GetPythonTypeFromType(type)) + BindingRestrictions.Empty ); } - protected override Expression SetBoundValue(Expression context, ActionBinder binder, Type type, Expression value, Expression instance) { - return Ast.Call( - typeof(PythonOps).GetMethod("SlotSetValue"), - context, - AstUtils.Constant(GetSlot(), typeof(PythonTypeSlot)), - AstUtils.Convert( - instance, - typeof(object) + protected override DynamicMetaObject SetBoundValue(OverloadResolverFactory factory, ActionBinder binder, Type type, DynamicMetaObject value, DynamicMetaObject instance) { + return new DynamicMetaObject( + Ast.Call( + typeof(PythonOps).GetMethod("SlotSetValue"), + ((PythonOverloadResolverFactory)factory)._codeContext, + AstUtils.Constant(GetSlot(), typeof(PythonTypeSlot)), + AstUtils.Convert( + instance.Expression, + typeof(object) + ), + AstUtils.Constant(DynamicHelpers.GetPythonTypeFromType(type)), + value.Expression ), - AstUtils.Constant(DynamicHelpers.GetPythonTypeFromType(type)), - value - ); - } - - public Expression GetBoundPythonValue(RuleBuilder builder, ActionBinder binder, PythonType accessing) { - return Ast.Call( - typeof(PythonOps).GetMethod("SlotGetValue"), - builder.Context, - AstUtils.Constant(GetSlot(), typeof(PythonTypeSlot)), - AstUtils.Constant(null), - AstUtils.Constant(accessing) + BindingRestrictions.Empty ); } } @@ -97,8 +98,8 @@ class CustomAttributeTracker : PythonCustomTracker { _slot = slot; } - public override Expression GetValue(Expression context, ActionBinder binder, Type type) { - return GetBoundValue(context, binder, type, AstUtils.Constant(null)); + public override DynamicMetaObject GetValue(OverloadResolverFactory factory, ActionBinder binder, Type type) { + return GetBoundValue(factory, binder, type, new DynamicMetaObject(AstUtils.Constant(null), BindingRestrictions.Empty)); } public override string Name { @@ -143,8 +144,8 @@ class ClassMethodTracker : PythonCustomTracker { ); } - public override Expression GetValue(Expression context, ActionBinder binder, Type type) { - return GetBoundValue(context, binder, type, AstUtils.Constant(null)); + public override DynamicMetaObject GetValue(OverloadResolverFactory factory, ActionBinder binder, Type type) { + return GetBoundValue(factory, binder, type, new DynamicMetaObject(AstUtils.Constant(null), BindingRestrictions.Empty)); } public override Type DeclaringType { diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/OldClass.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/OldClass.cs index dc2c49ddf9..719da9a41e 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/OldClass.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/OldClass.cs @@ -55,7 +55,8 @@ public sealed class OldClass : #endif ICodeFormattable, IMembersList, - IDynamicMetaObjectProvider { + IDynamicMetaObjectProvider, + IPythonMembersList { [NonSerialized] private List _bases; @@ -410,7 +411,11 @@ public sealed class OldClass : #region IMembersList Members - IList IMembersList.GetMemberNames(CodeContext context) { + IList IMembersList.GetMemberNames() { + return PythonOps.GetStringMemberList(this); + } + + IList IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { PythonDictionary attrs = new PythonDictionary(_dict); RecurseAttrHierarchy(this, attrs); return PythonOps.MakeListFromSequence(attrs); diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/OldInstance.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/OldInstance.cs index 62f96c857f..8889317b84 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/OldInstance.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/OldInstance.cs @@ -40,8 +40,8 @@ public sealed partial class OldInstance : #endif ISerializable, IWeakReferenceable, - IMembersList, - IDynamicMetaObjectProvider + IDynamicMetaObjectProvider, + IPythonMembersList { private PythonDictionary _dict; @@ -587,7 +587,11 @@ public sealed partial class OldInstance : #region IMembersList Members - IList IMembersList.GetMemberNames(CodeContext context) { + IList IMembersList.GetMemberNames() { + return PythonOps.GetStringMemberList(this); + } + + IList IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { PythonDictionary attrs = new PythonDictionary(_dict); OldClass.RecurseAttrHierarchy(this._class, attrs); return PythonOps.MakeListFromSequence(attrs); diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/PythonType.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/PythonType.cs index 908b8c02b8..58cee3c003 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/PythonType.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/PythonType.cs @@ -45,7 +45,7 @@ namespace IronPython.Runtime.Types { [PythonType("type")] [Documentation(@"type(object) -> gets the type of the object type(name, bases, dict) -> creates a new type instance with the given name, base classes, and members from the dictionary")] - public partial class PythonType : IMembersList, IDynamicMetaObjectProvider, IWeakReferenceable, ICodeFormattable, IFastGettable, IFastSettable, IFastInvokable { + public partial class PythonType : IPythonMembersList, IDynamicMetaObjectProvider, IWeakReferenceable, ICodeFormattable, IFastGettable, IFastSettable, IFastInvokable { private Type/*!*/ _underlyingSystemType; // the underlying CLI system type for this type private string _name; // the name of the type private Dictionary _dict; // type-level slots & attributes @@ -2260,7 +2260,11 @@ private enum PythonTypeAttributes { #region IMembersList Members - IList IMembersList.GetMemberNames(CodeContext context) { + IList IMembersList.GetMemberNames() { + return PythonOps.GetStringMemberList(this); + } + + IList IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { IList res = GetMemberNames(context); object[] arr = new object[res.Count]; diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/PythonTypeSlot.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/PythonTypeSlot.cs index 1a50d1d479..ba6fe80c66 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/PythonTypeSlot.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/PythonTypeSlot.cs @@ -13,12 +13,10 @@ * * ***************************************************************************/ -using System; +using System.Dynamic; using System.Linq.Expressions; using System.Runtime.InteropServices; -using Microsoft.Scripting.Runtime; - using IronPython.Runtime.Binding; using IronPython.Runtime.Operations; @@ -80,14 +78,14 @@ public class PythonTypeSlot { /// The default implementation just calls the TryGetValue method. Subtypes of PythonTypeSlot can override /// this and provide a more optimal implementation. /// - internal virtual void MakeGetExpression(PythonBinder/*!*/ binder, Expression/*!*/ codeContext, Expression instance, Expression/*!*/ owner, ConditionalBuilder/*!*/ builder) { + internal virtual void MakeGetExpression(PythonBinder/*!*/ binder, Expression/*!*/ codeContext, DynamicMetaObject instance, DynamicMetaObject/*!*/ owner, ConditionalBuilder/*!*/ builder) { ParameterExpression tmp = Ast.Variable(typeof(object), "slotTmp"); Expression call = Ast.Call( typeof(PythonOps).GetMethod("SlotTryGetValue"), codeContext, AstUtils.Convert(AstUtils.WeakConstant(this), typeof(PythonTypeSlot)), - instance ?? AstUtils.Constant(null), - owner, + instance != null ? instance.Expression : AstUtils.Constant(null), + owner.Expression, tmp ); diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/ReflectedField.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/ReflectedField.cs index d8a9407db7..bffdd1d41a 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/ReflectedField.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/ReflectedField.cs @@ -162,7 +162,7 @@ public ReflectedField(FieldInfo/*!*/ info) } } - internal override void MakeGetExpression(PythonBinder/*!*/ binder, Expression/*!*/ codeContext, Expression instance, Expression/*!*/ owner, ConditionalBuilder/*!*/ builder) { + internal override void MakeGetExpression(PythonBinder/*!*/ binder, Expression/*!*/ codeContext, DynamicMetaObject instance, DynamicMetaObject/*!*/ owner, ConditionalBuilder/*!*/ builder) { if (!_info.IsPublic || _info.DeclaringType.ContainsGenericParameters) { // fallback to reflection base.MakeGetExpression(binder, codeContext, instance, owner, builder); @@ -177,10 +177,10 @@ public ReflectedField(FieldInfo/*!*/ info) AstUtils.Convert( Ast.Field( binder.ConvertExpression( - instance, + instance.Expression, _info.DeclaringType, ConversionResultKind.ExplicitCast, - codeContext + new PythonOverloadResolverFactory(binder, codeContext) ), _info ), diff --git a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/ReflectedProperty.cs b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/ReflectedProperty.cs index 886a597310..dc7f6c07e3 100644 --- a/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/ReflectedProperty.cs +++ b/Merlin/Main/Languages/IronPython/IronPython/Runtime/Types/ReflectedProperty.cs @@ -15,6 +15,7 @@ using System; using System.Diagnostics; +using System.Dynamic; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; @@ -22,7 +23,6 @@ using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; -using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Binding; @@ -160,7 +160,7 @@ public ReflectedProperty(PropertyInfo info, MethodInfo[] getters, MethodInfo[] s return true; } - internal override void MakeGetExpression(PythonBinder/*!*/ binder, Expression/*!*/ codeContext, Expression instance, Expression/*!*/ owner, ConditionalBuilder/*!*/ builder) { + internal override void MakeGetExpression(PythonBinder/*!*/ binder, Expression/*!*/ codeContext, DynamicMetaObject instance, DynamicMetaObject/*!*/ owner, ConditionalBuilder/*!*/ builder) { if (Getter.Length != 0 && !Getter[0].IsPublic) { // fallback to runtime call base.MakeGetExpression(binder, codeContext, instance, owner, builder); @@ -173,16 +173,16 @@ public ReflectedProperty(PropertyInfo info, MethodInfo[] getters, MethodInfo[] s MemberTracker.FromMemberInfo(_info) ), typeof(object) - ) + ).Expression ); } else if (instance != null) { builder.FinishCondition( AstUtils.Convert( binder.MakeCallExpression( - codeContext, + new PythonOverloadResolverFactory(binder, codeContext), Getter[0], instance - ), + ).Expression, typeof(object) ) ); @@ -190,9 +190,9 @@ public ReflectedProperty(PropertyInfo info, MethodInfo[] getters, MethodInfo[] s builder.FinishCondition( AstUtils.Convert( binder.MakeCallExpression( - codeContext, + new PythonOverloadResolverFactory(binder, codeContext), Getter[0] - ), + ).Expression, typeof(object) ) ); diff --git a/Merlin/Main/Languages/IronPython/IronPythonTest/InheritTest.cs b/Merlin/Main/Languages/IronPython/IronPythonTest/InheritTest.cs index 0bde8b36b4..c3cf72913b 100644 --- a/Merlin/Main/Languages/IronPython/IronPythonTest/InheritTest.cs +++ b/Merlin/Main/Languages/IronPython/IronPythonTest/InheritTest.cs @@ -18,7 +18,7 @@ using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; -using Microsoft.Scripting.Runtime; +using IronPython.Runtime; namespace IronPythonTest { diff --git a/Merlin/Main/Languages/IronPython/IronPythonTest/IronPythonTest.csproj b/Merlin/Main/Languages/IronPython/IronPythonTest/IronPythonTest.csproj index 5a99d88e38..3204fc34df 100644 --- a/Merlin/Main/Languages/IronPython/IronPythonTest/IronPythonTest.csproj +++ b/Merlin/Main/Languages/IronPython/IronPythonTest/IronPythonTest.csproj @@ -21,7 +21,7 @@ true SIGNED true - ..\..\..\Utilities\Silverlight\x86ret\ + ..\..\..\Utilities\Silverlight\x86ret\ true diff --git a/Merlin/Main/Languages/Ruby/ClassInitGenerator/Libraries/LibraryDef.cs b/Merlin/Main/Languages/Ruby/ClassInitGenerator/Libraries/LibraryDef.cs index 3dfcb2379a..583db3fc12 100644 --- a/Merlin/Main/Languages/Ruby/ClassInitGenerator/Libraries/LibraryDef.cs +++ b/Merlin/Main/Languages/Ruby/ClassInitGenerator/Libraries/LibraryDef.cs @@ -655,10 +655,6 @@ private class ConstantDef { var type = parameterInfos[i].ParameterType; - if (type == typeof(CodeContext)) { - LogMethodError("CodeContext is obsolete use RubyContext instead.", methodDef, overload); - } - if (type.IsSubclassOf(typeof(RubyCallSiteStorage))) { if (hasSelf || hasContext || hasBlock) { LogMethodError("RubyCallSiteStorage must precede all other parameters", methodDef, overload); diff --git a/Merlin/Main/Languages/Ruby/IronRuby.Tests.VS/IronRuby.Tests.VS.csproj b/Merlin/Main/Languages/Ruby/IronRuby.Tests.VS/IronRuby.Tests.VS.csproj deleted file mode 100644 index 45e7af2e47..0000000000 --- a/Merlin/Main/Languages/Ruby/IronRuby.Tests.VS/IronRuby.Tests.VS.csproj +++ /dev/null @@ -1,60 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {7FE874FB-A5C8-4EE6-A725-472CFA16BE7E} - Library - Properties - IronRuby.Tests.VS - IronRuby.Tests.VS - v3.5 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - SAK - SAK - SAK - SAK - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - {8103D91B-89D8-4A18-9A40-426992602EA2} - IronRuby.Tests - - - - - - - - \ No newline at end of file diff --git a/Merlin/Main/Languages/Ruby/IronRuby.Tests/RubyTests.cs b/Merlin/Main/Languages/Ruby/IronRuby.Tests/RubyTests.cs index e0310e7b0e..577c6318ba 100644 --- a/Merlin/Main/Languages/Ruby/IronRuby.Tests/RubyTests.cs +++ b/Merlin/Main/Languages/Ruby/IronRuby.Tests/RubyTests.cs @@ -46,8 +46,8 @@ public partial class Tests { Scenario_ParseRegex1, Scenario_RubyCategorizer1, - Scenario_RubyNameMangling1, - Scenario_RubyNameMangling2, + NameMangling1, + NameMangling2, OverloadResolution_Block1, OverloadResolution_ParamArrays1, @@ -354,6 +354,7 @@ public partial class Tests { Require1, RequireInterop1, + RequireInterop2, Load1, LibraryLoader1, @@ -620,6 +621,7 @@ public partial class Tests { Dlr_Comparable, Dlr_RubyObjects, Dlr_Methods, + Dlr_Visibility, Dlr_Languages, }; } diff --git a/Merlin/Main/Languages/Ruby/IronRuby.Tests/Runtime/DlrInteropTests.cs b/Merlin/Main/Languages/Ruby/IronRuby.Tests/Runtime/DlrInteropTests.cs index fcdba573bf..cd035cd0b0 100644 --- a/Merlin/Main/Languages/Ruby/IronRuby.Tests/Runtime/DlrInteropTests.cs +++ b/Merlin/Main/Languages/Ruby/IronRuby.Tests/Runtime/DlrInteropTests.cs @@ -787,6 +787,42 @@ SanityTest.sanity_test self //assert_equal Methods.with_block {|x| x + 1000}, 1100 } + public void Dlr_Visibility() { + Engine.Execute(@" +class C + def public_m + 0 + end + + private + def private_m + 1 + end + + protected + def protected_m + 2 + end +end +"); + var classC = Runtime.Globals.GetVariable("C"); + var c = Engine.Operations.CreateInstance(classC); + + AssertExceptionThrown(() => MyInvokeMemberBinder.Invoke(c, "private_m")); + AssertExceptionThrown(() => MyInvokeMemberBinder.Invoke(c, "protected_m")); + var r1 = MyInvokeMemberBinder.Invoke(c, "public_m"); + Assert(r1 is int && (int)r1 == 0); + + Engine.Execute(@" +class C + def method_missing name + 3 + end +end"); + var r2 = MyInvokeMemberBinder.Invoke(c, "private_m"); + Assert(r2 is int && (int)r2 == 3); + } + public void Dlr_Languages() { //# Pass in ref/out params //# Named arguments diff --git a/Merlin/Main/Languages/Ruby/IronRuby.Tests/Runtime/LoaderTests.cs b/Merlin/Main/Languages/Ruby/IronRuby.Tests/Runtime/LoaderTests.cs index 3b4427f955..baac513f75 100644 --- a/Merlin/Main/Languages/Ruby/IronRuby.Tests/Runtime/LoaderTests.cs +++ b/Merlin/Main/Languages/Ruby/IronRuby.Tests/Runtime/LoaderTests.cs @@ -140,6 +140,42 @@ puts C } } + public void RequireInterop2() { + if (_driver.PartialTrust || !_driver.RunPython) return; + + try { + string temp = _driver.MakeTempDir(); + Context.Loader.SetLoadPaths(new[] { temp }); + + File.WriteAllText(Path.Combine(temp, "a.py"), @" +def WhoIsThis(): + print 'Python' + +Foo = 1 + +class Bar(object): + def baz(self): + print Foo +"); + + TestOutput(@" +a = IronRuby.require('a') +scopes = IronRuby.loaded_scripts.collect { |z| z.value } +a.who_is_this.call +a.foo += 1 +a.bar.new.baz +puts scopes[0].Foo +", @" +Python +2 +2 +"); + + } finally { + File.Delete("b.py"); + } + } + public class TestLibraryInitializer1 : LibraryInitializer { protected override void LoadModules() { Context.ObjectClass.SetConstant("TEST_LIBRARY", "hello from library"); diff --git a/Merlin/Main/Languages/Ruby/IronRuby.Tests/Runtime/RubyUtilsTests.cs b/Merlin/Main/Languages/Ruby/IronRuby.Tests/Runtime/RubyUtilsTests.cs index 449466458d..1ead686aa5 100644 --- a/Merlin/Main/Languages/Ruby/IronRuby.Tests/Runtime/RubyUtilsTests.cs +++ b/Merlin/Main/Languages/Ruby/IronRuby.Tests/Runtime/RubyUtilsTests.cs @@ -17,34 +17,124 @@ namespace IronRuby.Tests { public partial class Tests { - public void Scenario_RubyNameMangling1() { - Assert(RubyUtils.TryUnmangleName("ip_stack") == "IpStack"); // TODO + public void NameMangling1() { Assert(RubyUtils.TryUnmangleName("stack") == "Stack"); Assert(RubyUtils.TryUnmangleName("this_is_my_long_name") == "ThisIsMyLongName"); - Assert(RubyUtils.TryUnmangleName("") == null); Assert(RubyUtils.TryUnmangleName("f") == "F"); - Assert(RubyUtils.TryUnmangleName("fo") == "Fo"); - Assert(RubyUtils.TryUnmangleName("foo") == "Foo"); - Assert(RubyUtils.TryUnmangleName("foo_bar") == "FooBar"); - Assert(RubyUtils.TryUnmangleName("ma_m") == "MaM"); - Assert(RubyUtils.TryUnmangleName("initialize") == "initialize"); - Assert(RubyUtils.TryUnmangleName("Initialize") == "Initialize"); + Assert(RubyUtils.TryUnmangleName("initialize") == "Initialize"); + + // non-alpha characters are treated as lower-case letters: + Assert(RubyUtils.TryUnmangleName("foo_bar=") == "FooBar="); + Assert(RubyUtils.TryUnmangleName("foo?") == "Foo?"); + Assert(RubyUtils.TryUnmangleName("???") == "???"); + Assert(RubyUtils.TryUnmangleName("1_2_3") == "123"); + + // special cases: + Assert(RubyUtils.TryUnmangleName("on") == "On"); + Assert(RubyUtils.TryUnmangleName("up") == "Up"); + Assert(RubyUtils.TryUnmangleName("in") == "In"); + Assert(RubyUtils.TryUnmangleName("to") == "To"); + Assert(RubyUtils.TryUnmangleName("of") == "Of"); + Assert(RubyUtils.TryUnmangleName("it") == "It"); + Assert(RubyUtils.TryUnmangleName("is") == "Is"); + Assert(RubyUtils.TryUnmangleName("if") == "If"); + Assert(RubyUtils.TryUnmangleName("go") == "Go"); + Assert(RubyUtils.TryUnmangleName("do") == "Do"); + Assert(RubyUtils.TryUnmangleName("by") == "By"); + Assert(RubyUtils.TryUnmangleName("at") == "At"); + Assert(RubyUtils.TryUnmangleName("as") == "As"); + Assert(RubyUtils.TryUnmangleName("my") == "My"); + + Assert(RubyUtils.TryUnmangleName("ip") == "IP"); + Assert(RubyUtils.TryUnmangleName("rx") == "RX"); + Assert(RubyUtils.TryUnmangleName("pi") == "PI"); + + Assert(RubyUtils.TryUnmangleName("na_n") == null); + Assert(RubyUtils.TryUnmangleName("nan") == "Nan"); + Assert(RubyUtils.TryUnmangleName("ip_address") == "IPAddress"); + Assert(RubyUtils.TryUnmangleName("i_id_id") == "IIdId"); + Assert(RubyUtils.TryUnmangleName("i_ip_ip") == null); + Assert(RubyUtils.TryUnmangleName("ip_foo_ip") == "IPFooIP"); + Assert(RubyUtils.TryUnmangleName("active_x") == "ActiveX"); + + Assert(RubyUtils.TryUnmangleName("get_u_int16") == "GetUInt16"); + Assert(RubyUtils.TryUnmangleName("get_ui_parent_core") == "GetUIParentCore"); + + // TODO: ??? + Assert(RubyUtils.TryUnmangleName("i_pv6") == "IPv6"); + + // names that cannot be mangled: + Assert(RubyUtils.TryUnmangleName("") == null); + Assert(RubyUtils.TryUnmangleName("IPX") == null); + Assert(RubyUtils.TryUnmangleName("FO") == null); + Assert(RubyUtils.TryUnmangleName("FOOBar") == null); + Assert(RubyUtils.TryUnmangleName("FooBAR") == null); + Assert(RubyUtils.TryUnmangleName("foo__bar") == null); + Assert(RubyUtils.TryUnmangleName("_foo") == null); + Assert(RubyUtils.TryUnmangleName("foo_") == null); } - public void Scenario_RubyNameMangling2() { - Assert(RubyUtils.MangleName("IPStack") == "ip_stack"); // TODO - Assert(RubyUtils.MangleName("Stack") == "stack"); - Assert(RubyUtils.MangleName("ThisIsMyLongName") == "this_is_my_long_name"); - Assert(RubyUtils.MangleName("") == ""); - Assert(RubyUtils.MangleName("F") == "f"); - Assert(RubyUtils.MangleName("FO") == "fo"); - Assert(RubyUtils.MangleName("FOO") == "foo"); - Assert(RubyUtils.MangleName("FOOBar") == "foo_bar"); - Assert(RubyUtils.MangleName("MaM") == "ma_m"); - Assert(RubyUtils.MangleName("foo") == "foo"); - Assert(RubyUtils.MangleName("foo_bar=") == "foo_bar="); - Assert(RubyUtils.MangleName("initialize") == "initialize"); - Assert(RubyUtils.MangleName("Initialize") == "Initialize"); + public void NameMangling2() { + Assert(RubyUtils.TryMangleName("Stack") == "stack"); + Assert(RubyUtils.TryMangleName("ThisIsMyLongName") == "this_is_my_long_name"); + Assert(RubyUtils.TryMangleName("F") == "f"); + Assert(RubyUtils.TryMangleName("Initialize") == "initialize"); + Assert(RubyUtils.TryMangleName("fooBar") == "foo_bar"); + + // characters that are not upper case letters are treated as lower-case: + Assert(RubyUtils.TryMangleName("Foo123bar") == "foo123bar"); + Assert(RubyUtils.TryMangleName("123Bar") == "123_bar"); + Assert(RubyUtils.TryMangleName("?Bar") == "?_bar"); + Assert(RubyUtils.TryMangleName("B__") == "b__"); + + // special cases: + Assert(RubyUtils.TryUnmangleName("ON") == null); + Assert(RubyUtils.TryUnmangleName("UP") == null); + Assert(RubyUtils.TryUnmangleName("IN") == null); + Assert(RubyUtils.TryUnmangleName("TO") == null); + Assert(RubyUtils.TryUnmangleName("OF") == null); + Assert(RubyUtils.TryUnmangleName("IT") == null); + Assert(RubyUtils.TryUnmangleName("IF") == null); + Assert(RubyUtils.TryUnmangleName("IS") == null); + Assert(RubyUtils.TryUnmangleName("GO") == null); + Assert(RubyUtils.TryUnmangleName("DO") == null); + Assert(RubyUtils.TryUnmangleName("BY") == null); + Assert(RubyUtils.TryUnmangleName("AT") == null); + Assert(RubyUtils.TryUnmangleName("AS") == null); + Assert(RubyUtils.TryUnmangleName("MY") == null); + Assert(RubyUtils.TryUnmangleName("ID") == null); + Assert(RubyUtils.TryUnmangleName("OK") == null); + + Assert(RubyUtils.TryMangleName("NaN") == null); + Assert(RubyUtils.TryMangleName("NaNValue") == null); + Assert(RubyUtils.TryMangleName("At") == "at"); + Assert(RubyUtils.TryMangleName("IP") == "ip"); + Assert(RubyUtils.TryMangleName("FO") == "fo"); + Assert(RubyUtils.TryMangleName("PI") == "pi"); + Assert(RubyUtils.TryMangleName("IPAddress") == "ip_address"); + Assert(RubyUtils.TryMangleName("MyDB") == "my_db"); + Assert(RubyUtils.TryMangleName("PyPy") == "py_py"); + Assert(RubyUtils.TryMangleName("IPFooIP") == "ip_foo_ip"); + Assert(RubyUtils.TryMangleName("ActiveX") == "active_x"); + + Assert(RubyUtils.TryMangleName("GetUInt16") == "get_u_int16"); + Assert(RubyUtils.TryMangleName("GetUIParentCore") == "get_ui_parent_core"); + + // TODO: ??? + Assert(RubyUtils.TryMangleName("IPv6") == "i_pv6"); + + // names that cannot be mangled: + Assert(RubyUtils.TryMangleName("") == null); + Assert(RubyUtils.TryMangleName("IPX") == null); + Assert(RubyUtils.TryMangleName("FOO") == null); + Assert(RubyUtils.TryMangleName("FOOBar") == null); + Assert(RubyUtils.TryMangleName("FooBAR") == null); + Assert(RubyUtils.TryMangleName("foo") == null); + Assert(RubyUtils.TryMangleName("initialize") == null); + Assert(RubyUtils.TryMangleName("foo_bar=") == null); + Assert(RubyUtils.TryMangleName("foo__bar") == null); + Assert(RubyUtils.TryMangleName("_foo") == null); + Assert(RubyUtils.TryMangleName("foo_") == null); } } } diff --git a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Builtins/KernelOps.cs b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Builtins/KernelOps.cs index 18f511e9db..ffa762d6ae 100644 --- a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Builtins/KernelOps.cs +++ b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Builtins/KernelOps.cs @@ -398,12 +398,11 @@ public static class KernelOps { return block.Proc.ToLambda(); } - #region load, require + #region load, load_assembly, require [RubyMethod("load", RubyMethodAttributes.PrivateInstance)] [RubyMethod("load", RubyMethodAttributes.PublicSingleton)] - public static bool Load(RubyScope/*!*/ scope, object self, - [DefaultProtocol, NotNull]MutableString/*!*/ libraryName, [Optional]bool wrap) { + public static bool Load(RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]MutableString/*!*/ libraryName, [Optional]bool wrap) { return scope.RubyContext.Loader.LoadFile(scope.GlobalScope.Scope, self, libraryName, wrap ? LoadFlags.LoadIsolated : LoadFlags.None); } @@ -413,13 +412,12 @@ public static class KernelOps { [DefaultProtocol, NotNull]MutableString/*!*/ assemblyName, [DefaultProtocol, Optional, NotNull]MutableString libraryNamespace) { string initializer = libraryNamespace != null ? LibraryInitializer.GetFullTypeName(libraryNamespace.ConvertToString()) : null; - return context.Loader.LoadAssembly(assemblyName.ConvertToString(), initializer, true, true); + return context.Loader.LoadAssembly(assemblyName.ConvertToString(), initializer, true, true) != null; } [RubyMethod("require", RubyMethodAttributes.PrivateInstance)] [RubyMethod("require", RubyMethodAttributes.PublicSingleton)] - public static bool Require(RubyScope/*!*/ scope, object self, - [DefaultProtocol, NotNull]MutableString/*!*/ libraryName) { + public static bool Require(RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]MutableString/*!*/ libraryName) { return scope.RubyContext.Loader.LoadFile(scope.GlobalScope.Scope, self, libraryName, LoadFlags.LoadOnce | LoadFlags.AppendExtensions); } @@ -1537,7 +1535,7 @@ internal ThrowCatchUnwinder(string/*!*/ label, object returnValue) // thread-safe: [RubyMethod("method")] public static RubyMethod/*!*/ GetMethod(RubyContext/*!*/ context, object self, [DefaultProtocol, NotNull]string/*!*/ name) { - RubyMemberInfo info = context.ResolveMethod(self, name, RubyClass.IgnoreVisibility).Info; + RubyMemberInfo info = context.ResolveMethod(self, name, VisibilityContext.AllVisible).Info; if (info == null) { throw RubyExceptions.CreateUndefinedMethodError(context.GetClassOf(self), name); } diff --git a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Builtins/Marshal.cs b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Builtins/Marshal.cs index 42bb9a2d66..93560762a7 100644 --- a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Builtins/Marshal.cs +++ b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Builtins/Marshal.cs @@ -25,6 +25,7 @@ using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using Microsoft.Scripting.Generation; +using IronRuby.Runtime.Calls; namespace IronRuby.Builtins { @@ -384,8 +385,8 @@ class SubclassData { // TODO: replace with a table-driven implementation // TODO: visibility? - bool implementsDump = _context.ResolveMethod(obj, "_dump", RubyClass.IgnoreVisibility).Found; - bool implementsMarshalDump = _context.ResolveMethod(obj, "marshal_dump", RubyClass.IgnoreVisibility).Found; + bool implementsDump = _context.ResolveMethod(obj, "_dump", VisibilityContext.AllVisible).Found; + bool implementsMarshalDump = _context.ResolveMethod(obj, "marshal_dump", VisibilityContext.AllVisible).Found; bool writeInstanceData = false; string[] instanceNames = null; diff --git a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Builtins/ModuleOps.cs b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Builtins/ModuleOps.cs index eb47a6969a..e34d98bb4a 100644 --- a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Builtins/ModuleOps.cs +++ b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Builtins/ModuleOps.cs @@ -266,7 +266,7 @@ public static class ModuleOps { options |= MethodLookup.ReturnForwarder; } - method = module.ResolveMethodNoLock(methodName, RubyClass.IgnoreVisibility, options).Info; + method = module.ResolveMethodNoLock(methodName, VisibilityContext.AllVisible, options).Info; if (method == null) { throw RubyExceptions.CreateNameError(RubyExceptions.FormatMethodMissingMessage(context, module, methodName)); } @@ -310,7 +310,9 @@ public static class ModuleOps { public static RubyMethod/*!*/ DefineMethod(RubyScope/*!*/ scope, RubyModule/*!*/ self, [NotNull]ClrName/*!*/ methodName, [NotNull]RubyMethod/*!*/ method) { var result = DefineMethod(scope, self, methodName.MangledName, method); - self.AddMethodAlias(methodName.ActualName, methodName.MangledName); + if (methodName.HasMangledName) { + self.AddMethodAlias(methodName.ActualName, methodName.MangledName); + } return result; } @@ -329,7 +331,9 @@ public static class ModuleOps { public static UnboundMethod/*!*/ DefineMethod(RubyScope/*!*/ scope, RubyModule/*!*/ self, [NotNull]ClrName/*!*/ methodName, [NotNull]UnboundMethod/*!*/ method) { var result = DefineMethod(scope, self, methodName.MangledName, method); - self.AddMethodAlias(methodName.ActualName, methodName.MangledName); + if (methodName.HasMangledName) { + self.AddMethodAlias(methodName.ActualName, methodName.MangledName); + } return result; } @@ -366,7 +370,9 @@ public static class ModuleOps { RubyModule/*!*/ self, [NotNull]ClrName/*!*/ methodName) { var result = DefineMethod(scope, block, self, methodName.MangledName); - self.AddMethodAlias(methodName.ActualName, methodName.MangledName); + if (methodName.HasMangledName) { + self.AddMethodAlias(methodName.ActualName, methodName.MangledName); + } return result; } @@ -386,7 +392,9 @@ public static class ModuleOps { [NotNull]ClrName/*!*/ methodName, [NotNull]Proc/*!*/ method) { var result = DefineMethod(scope, self, methodName.MangledName, method); - self.AddMethodAlias(methodName.ActualName, methodName.MangledName); + if (methodName.HasMangledName) { + self.AddMethodAlias(methodName.ActualName, methodName.MangledName); + } return result; } @@ -528,7 +536,7 @@ public static class ModuleOps { // thread-safe: [RubyMethod("undef_method", RubyMethodAttributes.PrivateInstance)] public static RubyModule/*!*/ UndefineMethod(RubyModule/*!*/ self, [DefaultProtocol, NotNull]string/*!*/ methodName) { - if (!self.ResolveMethod(methodName, RubyClass.IgnoreVisibility).Found) { + if (!self.ResolveMethod(methodName, VisibilityContext.AllVisible).Found) { throw RubyExceptions.CreateUndefinedMethodError(self, methodName); } self.UndefineMethod(methodName); @@ -882,28 +890,28 @@ public static class ModuleOps { // thread-safe: [RubyMethod("method_defined?")] public static bool MethodDefined(RubyModule/*!*/ self, [DefaultProtocol, NotNull]string/*!*/ methodName) { - RubyMemberInfo method = self.ResolveMethod(methodName, RubyClass.IgnoreVisibility).Info; + RubyMemberInfo method = self.ResolveMethod(methodName, VisibilityContext.AllVisible).Info; return method != null && method.Visibility != RubyMethodVisibility.Private; } // thread-safe: [RubyMethod("private_method_defined?")] public static bool PrivateMethodDefined(RubyModule/*!*/ self, [DefaultProtocol, NotNull]string/*!*/ methodName) { - RubyMemberInfo method = self.ResolveMethod(methodName, RubyClass.IgnoreVisibility).Info; + RubyMemberInfo method = self.ResolveMethod(methodName, VisibilityContext.AllVisible).Info; return method != null && method.Visibility == RubyMethodVisibility.Private; } // thread-safe: [RubyMethod("protected_method_defined?")] public static bool ProtectedMethodDefined(RubyModule/*!*/ self, [DefaultProtocol, NotNull]string/*!*/ methodName) { - RubyMemberInfo method = self.ResolveMethod(methodName, RubyClass.IgnoreVisibility).Info; + RubyMemberInfo method = self.ResolveMethod(methodName, VisibilityContext.AllVisible).Info; return method != null && method.Visibility == RubyMethodVisibility.Protected; } // thread-safe: [RubyMethod("public_method_defined?")] public static bool PublicMethodDefined(RubyModule/*!*/ self, [DefaultProtocol, NotNull]string/*!*/ methodName) { - RubyMemberInfo method = self.ResolveMethod(methodName, RubyClass.IgnoreVisibility).Info; + RubyMemberInfo method = self.ResolveMethod(methodName, VisibilityContext.AllVisible).Info; return method != null && method.Visibility == RubyMethodVisibility.Public; } @@ -914,7 +922,7 @@ public static class ModuleOps { // thread-safe: [RubyMethod("instance_method")] public static UnboundMethod/*!*/ GetInstanceMethod(RubyModule/*!*/ self, [DefaultProtocol, NotNull]string/*!*/ methodName) { - RubyMemberInfo method = self.ResolveMethod(methodName, RubyClass.IgnoreVisibility).Info; + RubyMemberInfo method = self.ResolveMethod(methodName, VisibilityContext.AllVisible).Info; if (method == null) { throw RubyExceptions.CreateUndefinedMethodError(self, methodName); } diff --git a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/ClrNameOps.cs b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/ClrNameOps.cs index e2e054a0e7..a468abc103 100644 --- a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/ClrNameOps.cs +++ b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/ClrNameOps.cs @@ -88,5 +88,29 @@ public static class ClrNameOps { public static object Compare(BinaryOpStorage/*!*/ comparisonStorage, RespondToStorage/*!*/ respondToStorage, ClrName/*!*/ self, object other) { return MutableStringOps.Compare(comparisonStorage, respondToStorage, self.MangledName, other); } + + /// + /// Converts a Ruby name to PascalCase name (e.g. "foo_bar" to "FooBar"). + /// Returns null if the name is not a well-formed Ruby name (it contains upper-case latter or subsequent underscores). + /// Characters that are not upper case letters are treated as lower-case letters. + /// + [RubyMethod("ruby_to_clr", RubyMethodAttributes.PublicSingleton)] + [RubyMethod("unmangle", RubyMethodAttributes.PublicSingleton)] + public static MutableString Unmangle(RubyClass/*!*/ self, [DefaultProtocol]string/*!*/ rubyName) { + var clr = RubyUtils.TryUnmangleName(rubyName); + return clr != null ? MutableString.Create(clr) : null; + } + + /// + /// Converts a camelCase or PascalCase name to a Ruby name (e.g. "FooBar" to "foo_bar"). + /// Returns null if the name is not in camelCase or PascalCase (FooBAR, foo, etc.). + /// Characters that are not upper case letters are treated as lower-case letters. + /// + [RubyMethod("clr_to_ruby", RubyMethodAttributes.PublicSingleton)] + [RubyMethod("mangle", RubyMethodAttributes.PublicSingleton)] + public static MutableString Mangle(RubyClass/*!*/ self, [DefaultProtocol]string/*!*/ clrName) { + var ruby = RubyUtils.TryMangleName(clrName); + return ruby != null ? MutableString.Create(ruby) : null; + } } } diff --git a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/IEnumerableOps.cs b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/IEnumerableOps.cs index 4a295c8ce4..db260a645b 100644 --- a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/IEnumerableOps.cs +++ b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/IEnumerableOps.cs @@ -30,6 +30,10 @@ public static class IEnumerableOps { public static object Each(BlockParam block, IEnumerable/*!*/ self) { foreach (object obj in self) { object result; + if (block == null) { + throw RubyExceptions.NoBlockGiven(); + } + if (block.Yield(obj, out result)) { return result; } diff --git a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/IronRubyOps.cs b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/IronRubyOps.cs index 34b17fa7f9..2b0ee8bd1c 100644 --- a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/IronRubyOps.cs +++ b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/IronRubyOps.cs @@ -19,16 +19,64 @@ using Microsoft.Scripting.Runtime; using System.Diagnostics; using System; +using System.Collections.Generic; +using Microsoft.Scripting.Utils; +using System.Reflection; +using System.Runtime.InteropServices; namespace IronRuby.Builtins { [RubyModule("IronRuby", Extends = typeof(Ruby), Restrictions = ModuleRestrictions.None)] public static class IronRubyOps { - [RubyMethod("dlr_config", RubyMethodAttributes.PublicSingleton)] - public static DlrConfiguration/*!*/ GetCurrentRuntimeConfiguration(RubyContext/*!*/ context, object self) { + [RubyMethod("configuration", RubyMethodAttributes.PublicSingleton)] + public static DlrConfiguration/*!*/ GetConfiguration(RubyContext/*!*/ context, RubyModule/*!*/ self) { return context.DomainManager.Configuration; } + [RubyMethod("globals", RubyMethodAttributes.PublicSingleton)] + public static Scope/*!*/ GetGlobalScope(RubyContext/*!*/ context, RubyModule/*!*/ self) { + return context.DomainManager.Globals; + } + + [RubyMethod("loaded_assemblies", RubyMethodAttributes.PublicSingleton)] + public static RubyArray/*!*/ GetLoadedAssemblies(RubyContext/*!*/ context, RubyModule/*!*/ self) { + return new RubyArray(context.DomainManager.GetLoadedAssemblyList()); + } + + /// + /// Gets a live read-only and thread-safe dictionary that maps full paths of the loaded scripts to their scopes. + /// + [RubyMethod("loaded_scripts", RubyMethodAttributes.PublicSingleton)] + public static IDictionary/*!*/ GetLoadedScripts(RubyContext/*!*/ context, RubyModule/*!*/ self) { + return new ReadOnlyDictionary(context.Loader.LoadedScripts); + } + + /// + /// The same as Kernel#require except for that it returns the loaded Assembly or Scope (even if already loaded). + /// + [RubyMethod("require", RubyMethodAttributes.PublicSingleton)] + public static object/*!*/ Require(RubyScope/*!*/ scope, RubyModule/*!*/ self, MutableString/*!*/ libraryName) { + object loaded; + + scope.RubyContext.Loader.LoadFile( + null, self, libraryName, LoadFlags.LoadOnce | LoadFlags.AppendExtensions | LoadFlags.ResolveLoaded, out loaded + ); + + Debug.Assert(loaded != null); + return loaded; + } + + /// + /// The same as Kernel#require except for that it returns the loaded Assembly or Scope. + /// + [RubyMethod("load", RubyMethodAttributes.PublicSingleton)] + public static object/*!*/ Load(RubyScope/*!*/ scope, RubyModule/*!*/ self, MutableString/*!*/ libraryName) { + object loaded; + scope.RubyContext.Loader.LoadFile(null, self, libraryName, LoadFlags.ResolveLoaded, out loaded); + Debug.Assert(loaded != null); + return loaded; + } + [RubyModule("Clr", Restrictions = ModuleRestrictions.None)] public static class ClrOps { [RubyMethod("profile", RubyMethodAttributes.PublicSingleton)] diff --git a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/ScopeOps.cs b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/ScopeOps.cs new file mode 100644 index 0000000000..87af18df15 --- /dev/null +++ b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/ScopeOps.cs @@ -0,0 +1,41 @@ +/* **************************************************************************** + * + * Copyright (c) Microsoft Corporation. + * + * This source code is subject to terms and conditions of the Microsoft Public License. A + * copy of the license can be found in the License.html file at the root of this distribution. If + * you cannot locate the Microsoft Public License, 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 Microsoft Public License. + * + * You must not remove this notice, or any other, from this software. + * + * + * ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using Microsoft.Scripting.Utils; +using IronRuby.Builtins; +using IronRuby.Runtime; +using Microsoft.Scripting.Runtime; +using Microsoft.Scripting; + +namespace IronRuby.Builtins { + /// + /// TODO: Scope should be IDO so this shouldn't be needed. + /// + [RubyClass("Scope", Extends = typeof(Scope), DefineIn = typeof(IronRubyOps.ClrOps))] + public static class ScopeOps { + #region method_missing + + [RubyMethod("method_missing", RubyMethodAttributes.PrivateInstance)] + public static object MethodMissing(RubyScope/*!*/ scope, BlockParam block, Scope/*!*/ self, SymbolId symbol, [NotNull]params object[]/*!*/ args) { + return RubyTopLevelScope.ScopeMethodMissing(scope.RubyContext, self, block, null, symbol, args); + } + + #endregion + } +} diff --git a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Initializers.Generated.cs b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Initializers.Generated.cs index 2bf039e0e0..d7f38ac0da 100644 --- a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Initializers.Generated.cs +++ b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Initializers.Generated.cs @@ -44,8 +44,8 @@ public sealed class BuiltinsLibraryInitializer : IronRuby.Builtins.LibraryInitia // Skipped primitive: __ClassSingleton // Skipped primitive: __MainSingleton - IronRuby.Builtins.RubyModule def42 = DefineGlobalModule("Comparable", typeof(IronRuby.Builtins.Comparable), 0x00000103, LoadComparable_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - IronRuby.Builtins.RubyModule def33 = DefineGlobalModule("Enumerable", typeof(IronRuby.Builtins.Enumerable), 0x00000103, LoadEnumerable_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyModule def43 = DefineGlobalModule("Comparable", typeof(IronRuby.Builtins.Comparable), 0x00000103, LoadComparable_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyModule def34 = DefineGlobalModule("Enumerable", typeof(IronRuby.Builtins.Enumerable), 0x00000103, LoadEnumerable_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); IronRuby.Builtins.RubyModule def8 = DefineGlobalModule("Errno", typeof(IronRuby.Builtins.Errno), 0x00000103, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); IronRuby.Builtins.RubyModule def25 = DefineModule("File::Constants", typeof(IronRuby.Builtins.RubyFileOps.Constants), 0x00000103, null, null, LoadFile__Constants_Constants, IronRuby.Builtins.RubyModule.EmptyArray); DefineGlobalModule("FileTest", typeof(IronRuby.Builtins.FileTest), 0x00000103, null, LoadFileTest_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); @@ -63,7 +63,7 @@ public sealed class BuiltinsLibraryInitializer : IronRuby.Builtins.LibraryInitia DefineGlobalModule("Math", typeof(IronRuby.Builtins.RubyMath), 0x00000103, LoadMath_Instance, LoadMath_Class, LoadMath_Constants, IronRuby.Builtins.RubyModule.EmptyArray); ExtendClass(typeof(Microsoft.Scripting.Actions.TypeTracker), null, LoadMicrosoft__Scripting__Actions__TypeTracker_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); DefineGlobalModule("ObjectSpace", typeof(IronRuby.Builtins.ObjectSpace), 0x00000103, null, LoadObjectSpace_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); - IronRuby.Builtins.RubyModule def39 = DefineGlobalModule("Precision", typeof(IronRuby.Builtins.Precision), 0x00000103, LoadPrecision_Instance, LoadPrecision_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyModule def40 = DefineGlobalModule("Precision", typeof(IronRuby.Builtins.Precision), 0x00000103, LoadPrecision_Instance, LoadPrecision_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); #if !SILVERLIGHT IronRuby.Builtins.RubyModule def26 = DefineGlobalModule("Process", typeof(IronRuby.Builtins.RubyProcess), 0x00000103, LoadProcess_Instance, LoadProcess_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); #endif @@ -73,227 +73,228 @@ public sealed class BuiltinsLibraryInitializer : IronRuby.Builtins.LibraryInitia ExtendClass(typeof(System.Type), null, LoadSystem__Type_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); // Skipped primitive: __ClassSingletonSingleton #if !SILVERLIGHT - object def1 = DefineSingleton(Load__Singleton_ArgFilesSingletonOps_Instance, null, null, def33); + object def1 = DefineSingleton(Load__Singleton_ArgFilesSingletonOps_Instance, null, null, def34); #endif - object def7 = DefineSingleton(Load__Singleton_EnvironmentSingletonOps_Instance, null, null, def33); - ExtendClass(typeof(Microsoft.Scripting.Actions.TypeGroup), null, LoadMicrosoft__Scripting__Actions__TypeGroup_Instance, null, null, new IronRuby.Builtins.RubyModule[] {def33}); + object def7 = DefineSingleton(Load__Singleton_EnvironmentSingletonOps_Instance, null, null, def34); + ExtendClass(typeof(Microsoft.Scripting.Actions.TypeGroup), null, LoadMicrosoft__Scripting__Actions__TypeGroup_Instance, null, null, new IronRuby.Builtins.RubyModule[] {def34}); // Skipped primitive: Object - ExtendClass(typeof(System.Char), null, null, null, null, new IronRuby.Builtins.RubyModule[] {def6, def33, def42}, + ExtendClass(typeof(System.Char), null, null, null, null, new IronRuby.Builtins.RubyModule[] {def6, def34, def43}, new System.Func(IronRuby.Builtins.CharOps.Create), new System.Func(IronRuby.Builtins.CharOps.Create), new System.Func(IronRuby.Builtins.CharOps.Create), new System.Func(IronRuby.Builtins.CharOps.Create) ); - ExtendModule(typeof(System.Collections.Generic.IDictionary), LoadSystem__Collections__Generic__IDictionary_Instance, null, null, def33); - ExtendModule(typeof(System.Collections.IEnumerable), LoadSystem__Collections__IEnumerable_Instance, null, null, def33); - ExtendModule(typeof(System.Collections.IList), LoadSystem__Collections__IList_Instance, null, null, def33); - ExtendModule(typeof(System.IComparable), LoadSystem__IComparable_Instance, null, null, def42); - ExtendClass(typeof(System.String), null, null, null, null, new IronRuby.Builtins.RubyModule[] {def6, def33, def42}, + ExtendModule(typeof(System.Collections.Generic.IDictionary), LoadSystem__Collections__Generic__IDictionary_Instance, null, null, def34); + ExtendModule(typeof(System.Collections.IEnumerable), LoadSystem__Collections__IEnumerable_Instance, null, null, def34); + ExtendModule(typeof(System.Collections.IList), LoadSystem__Collections__IList_Instance, null, null, def34); + ExtendModule(typeof(System.IComparable), LoadSystem__IComparable_Instance, null, null, def43); + ExtendClass(typeof(System.String), null, null, null, null, new IronRuby.Builtins.RubyModule[] {def6, def34, def43}, new System.Func(IronRuby.Builtins.ClrStringOps.Create), new System.Func(IronRuby.Builtins.ClrStringOps.Create), new System.Func(IronRuby.Builtins.ClrStringOps.Create), new System.Func(IronRuby.Builtins.ClrStringOps.Create) ); - DefineGlobalClass("Array", typeof(IronRuby.Builtins.RubyArray), 0x00000003, Context.ObjectClass, LoadArray_Instance, LoadArray_Class, null, new IronRuby.Builtins.RubyModule[] {def33}, + DefineGlobalClass("Array", typeof(IronRuby.Builtins.RubyArray), 0x00000003, Context.ObjectClass, LoadArray_Instance, LoadArray_Class, null, new IronRuby.Builtins.RubyModule[] {def34}, new System.Func(IronRuby.Builtins.ArrayOps.CreateArray), new System.Func>, IronRuby.Runtime.BlockParam, IronRuby.Builtins.RubyClass, System.Object, System.Object>(IronRuby.Builtins.ArrayOps.CreateArray), new System.Func(IronRuby.Builtins.ArrayOps.CreateArray), new System.Func(IronRuby.Builtins.ArrayOps.CreateArray) ); DefineGlobalClass("Binding", typeof(IronRuby.Builtins.Binding), 0x00000003, Context.ObjectClass, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - DefineGlobalClass("Dir", typeof(IronRuby.Builtins.RubyDir), 0x00000103, Context.ObjectClass, LoadDir_Instance, LoadDir_Class, null, new IronRuby.Builtins.RubyModule[] {def33}); + DefineGlobalClass("Dir", typeof(IronRuby.Builtins.RubyDir), 0x00000103, Context.ObjectClass, LoadDir_Instance, LoadDir_Class, null, new IronRuby.Builtins.RubyModule[] {def34}); #if !SILVERLIGHT if (Context.RubyOptions.Compatibility >= RubyCompatibility.Ruby19) { DefineGlobalClass("Encoding", typeof(IronRuby.Builtins.RubyEncoding), 0x00000003, Context.ObjectClass, LoadEncoding_Instance, LoadEncoding_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); } #endif - IronRuby.Builtins.RubyClass def43 = Context.ExceptionClass = DefineGlobalClass("Exception", typeof(System.Exception), 0x00000003, Context.ObjectClass, LoadException_Instance, LoadException_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def44 = Context.ExceptionClass = DefineGlobalClass("Exception", typeof(System.Exception), 0x00000003, Context.ObjectClass, LoadException_Instance, LoadException_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__Exception)); Context.FalseClass = DefineGlobalClass("FalseClass", typeof(IronRuby.Builtins.FalseClass), 0x00000103, Context.ObjectClass, LoadFalseClass_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); #if !SILVERLIGHT - IronRuby.Builtins.RubyClass def31 = DefineClass("File::Stat", typeof(System.IO.FileSystemInfo), 0x00000003, Context.ObjectClass, LoadFile__Stat_Instance, null, null, new IronRuby.Builtins.RubyModule[] {def42}, + IronRuby.Builtins.RubyClass def32 = DefineClass("File::Stat", typeof(System.IO.FileSystemInfo), 0x00000003, Context.ObjectClass, LoadFile__Stat_Instance, null, null, new IronRuby.Builtins.RubyModule[] {def43}, new System.Func(IronRuby.Builtins.RubyFileOps.RubyStatOps.Create) ); #endif - DefineGlobalClass("Hash", typeof(IronRuby.Builtins.Hash), 0x00000003, Context.ObjectClass, LoadHash_Instance, LoadHash_Class, null, new IronRuby.Builtins.RubyModule[] {def33}, + DefineGlobalClass("Hash", typeof(IronRuby.Builtins.Hash), 0x00000003, Context.ObjectClass, LoadHash_Instance, LoadHash_Class, null, new IronRuby.Builtins.RubyModule[] {def34}, new System.Func(IronRuby.Builtins.HashOps.CreateHash), new System.Func(IronRuby.Builtins.HashOps.CreateHash), new System.Func(IronRuby.Builtins.HashOps.CreateHash) ); - IronRuby.Builtins.RubyClass def44 = DefineGlobalClass("IO", typeof(IronRuby.Builtins.RubyIO), 0x00000003, Context.ObjectClass, LoadIO_Instance, LoadIO_Class, LoadIO_Constants, new IronRuby.Builtins.RubyModule[] {def25, def33}, + IronRuby.Builtins.RubyClass def45 = DefineGlobalClass("IO", typeof(IronRuby.Builtins.RubyIO), 0x00000003, Context.ObjectClass, LoadIO_Instance, LoadIO_Class, LoadIO_Constants, new IronRuby.Builtins.RubyModule[] {def25, def34}, new System.Func(IronRuby.Builtins.RubyIOOps.CreateIO), new System.Func(IronRuby.Builtins.RubyIOOps.CreateIO) ); - IronRuby.Builtins.RubyClass def28 = DefineClass("IronRuby::Clr::Name", typeof(IronRuby.Runtime.ClrName), 0x00000003, Context.ObjectClass, LoadIronRuby__Clr__Name_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyClass def28 = DefineClass("IronRuby::Clr::Name", typeof(IronRuby.Runtime.ClrName), 0x00000003, Context.ObjectClass, LoadIronRuby__Clr__Name_Instance, LoadIronRuby__Clr__Name_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyClass def29 = DefineClass("IronRuby::Clr::Scope", typeof(Microsoft.Scripting.Runtime.Scope), 0x00000003, Context.ObjectClass, LoadIronRuby__Clr__Scope_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); DefineGlobalClass("MatchData", typeof(IronRuby.Builtins.MatchData), 0x00000003, Context.ObjectClass, LoadMatchData_Instance, LoadMatchData_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); DefineGlobalClass("Method", typeof(IronRuby.Builtins.RubyMethod), 0x00000003, Context.ObjectClass, LoadMethod_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); // Skipped primitive: Module Context.NilClass = DefineGlobalClass("NilClass", typeof(Microsoft.Scripting.Runtime.DynamicNull), 0x00000003, Context.ObjectClass, LoadNilClass_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - IronRuby.Builtins.RubyClass def38 = DefineGlobalClass("Numeric", typeof(IronRuby.Builtins.Numeric), 0x00000103, Context.ObjectClass, LoadNumeric_Instance, null, null, new IronRuby.Builtins.RubyModule[] {def42}); + IronRuby.Builtins.RubyClass def39 = DefineGlobalClass("Numeric", typeof(IronRuby.Builtins.Numeric), 0x00000103, Context.ObjectClass, LoadNumeric_Instance, null, null, new IronRuby.Builtins.RubyModule[] {def43}); DefineGlobalClass("Proc", typeof(IronRuby.Builtins.Proc), 0x00000003, Context.ObjectClass, LoadProc_Instance, LoadProc_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Action(IronRuby.Builtins.ProcOps.Error) ); #if !SILVERLIGHT && !SILVERLIGHT IronRuby.Builtins.RubyClass def27 = DefineClass("Process::Status", typeof(IronRuby.Builtins.RubyProcess.Status), 0x00000103, Context.ObjectClass, LoadProcess__Status_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); #endif - DefineGlobalClass("Range", typeof(IronRuby.Builtins.Range), 0x00000003, Context.ObjectClass, LoadRange_Instance, null, null, new IronRuby.Builtins.RubyModule[] {def33}, + DefineGlobalClass("Range", typeof(IronRuby.Builtins.Range), 0x00000003, Context.ObjectClass, LoadRange_Instance, null, null, new IronRuby.Builtins.RubyModule[] {def34}, new System.Func(IronRuby.Builtins.RangeOps.CreateRange) ); - DefineGlobalClass("Regexp", typeof(IronRuby.Builtins.RubyRegex), 0x00000003, Context.ObjectClass, LoadRegexp_Instance, LoadRegexp_Class, LoadRegexp_Constants, new IronRuby.Builtins.RubyModule[] {def33}, + DefineGlobalClass("Regexp", typeof(IronRuby.Builtins.RubyRegex), 0x00000003, Context.ObjectClass, LoadRegexp_Instance, LoadRegexp_Class, LoadRegexp_Constants, new IronRuby.Builtins.RubyModule[] {def34}, new System.Func(IronRuby.Builtins.RegexpOps.Create), new System.Func(IronRuby.Builtins.RegexpOps.Create), new System.Func(IronRuby.Builtins.RegexpOps.Create), new System.Func(IronRuby.Builtins.RegexpOps.Create), new System.Func(IronRuby.Builtins.RegexpOps.Create) ); - DefineGlobalClass("String", typeof(IronRuby.Builtins.MutableString), 0x00000003, Context.ObjectClass, LoadString_Instance, null, null, new IronRuby.Builtins.RubyModule[] {def33, def42}, + DefineGlobalClass("String", typeof(IronRuby.Builtins.MutableString), 0x00000003, Context.ObjectClass, LoadString_Instance, null, null, new IronRuby.Builtins.RubyModule[] {def34, def43}, new System.Func(IronRuby.Builtins.MutableStringOps.Create), new System.Func(IronRuby.Builtins.MutableStringOps.Create) ); - DefineGlobalClass("Struct", typeof(IronRuby.Builtins.RubyStruct), 0x00000003, Context.ObjectClass, LoadStruct_Instance, LoadStruct_Class, LoadStruct_Constants, new IronRuby.Builtins.RubyModule[] {def33}, + DefineGlobalClass("Struct", typeof(IronRuby.Builtins.RubyStruct), 0x00000003, Context.ObjectClass, LoadStruct_Instance, LoadStruct_Class, LoadStruct_Constants, new IronRuby.Builtins.RubyModule[] {def34}, new System.Action(IronRuby.Builtins.RubyStructOps.AllocatorUndefined) ); DefineGlobalClass("Symbol", typeof(Microsoft.Scripting.SymbolId), 0x00000003, Context.ObjectClass, LoadSymbol_Instance, LoadSymbol_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); DefineGlobalClass("Thread", typeof(System.Threading.Thread), 0x00000003, Context.ObjectClass, LoadThread_Instance, LoadThread_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); DefineGlobalClass("ThreadGroup", typeof(IronRuby.Builtins.ThreadGroup), 0x00000103, Context.ObjectClass, LoadThreadGroup_Instance, null, LoadThreadGroup_Constants, IronRuby.Builtins.RubyModule.EmptyArray); - DefineGlobalClass("Time", typeof(System.DateTime), 0x00000003, Context.ObjectClass, LoadTime_Instance, LoadTime_Class, null, new IronRuby.Builtins.RubyModule[] {def42}, + DefineGlobalClass("Time", typeof(System.DateTime), 0x00000003, Context.ObjectClass, LoadTime_Instance, LoadTime_Class, null, new IronRuby.Builtins.RubyModule[] {def43}, new System.Func(IronRuby.Builtins.TimeOps.Create) ); Context.TrueClass = DefineGlobalClass("TrueClass", typeof(IronRuby.Builtins.TrueClass), 0x00000103, Context.ObjectClass, LoadTrueClass_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); DefineGlobalClass("UnboundMethod", typeof(IronRuby.Builtins.UnboundMethod), 0x00000103, Context.ObjectClass, LoadUnboundMethod_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray); // Skipped primitive: Class - IronRuby.Builtins.RubyClass def24 = DefineGlobalClass("File", typeof(IronRuby.Builtins.RubyFile), 0x00000003, def44, LoadFile_Instance, LoadFile_Class, LoadFile_Constants, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def24 = DefineGlobalClass("File", typeof(IronRuby.Builtins.RubyFile), 0x00000003, def45, LoadFile_Instance, LoadFile_Class, LoadFile_Constants, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func, IronRuby.Builtins.MutableString, System.Int32, IronRuby.Builtins.RubyFile>(IronRuby.Builtins.RubyFileOps.CreateFile), new System.Func, System.Int32, System.Int32, IronRuby.Builtins.RubyFile>(IronRuby.Builtins.RubyFileOps.CreateFile), new System.Func(IronRuby.Builtins.RubyFileOps.CreateFile), new System.Func(IronRuby.Builtins.RubyFileOps.CreateFile), new System.Func(IronRuby.Builtins.RubyFileOps.CreateFile) ); - DefineGlobalClass("Float", typeof(System.Double), 0x00000003, def38, LoadFloat_Instance, LoadFloat_Class, LoadFloat_Constants, new IronRuby.Builtins.RubyModule[] {def39}); - IronRuby.Builtins.RubyClass def45 = DefineGlobalClass("Integer", typeof(IronRuby.Builtins.Integer), 0x00000103, def38, LoadInteger_Instance, LoadInteger_Class, null, new IronRuby.Builtins.RubyModule[] {def39}); - DefineGlobalClass("NoMemoryError", typeof(IronRuby.Builtins.NoMemoryError), 0x00000103, def43, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("Float", typeof(System.Double), 0x00000003, def39, LoadFloat_Instance, LoadFloat_Class, LoadFloat_Constants, new IronRuby.Builtins.RubyModule[] {def40}); + IronRuby.Builtins.RubyClass def46 = DefineGlobalClass("Integer", typeof(IronRuby.Builtins.Integer), 0x00000103, def39, LoadInteger_Instance, LoadInteger_Class, null, new IronRuby.Builtins.RubyModule[] {def40}); + DefineGlobalClass("NoMemoryError", typeof(IronRuby.Builtins.NoMemoryError), 0x00000103, def44, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__NoMemoryError)); - IronRuby.Builtins.RubyClass def41 = DefineGlobalClass("ScriptError", typeof(IronRuby.Builtins.ScriptError), 0x00000003, def43, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def42 = DefineGlobalClass("ScriptError", typeof(IronRuby.Builtins.ScriptError), 0x00000003, def44, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__ScriptError)); - IronRuby.Builtins.RubyClass def40 = DefineGlobalClass("SignalException", typeof(IronRuby.Builtins.SignalException), 0x00000103, def43, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def41 = DefineGlobalClass("SignalException", typeof(IronRuby.Builtins.SignalException), 0x00000103, def44, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__SignalException)); - IronRuby.Builtins.RubyClass def34 = Context.StandardErrorClass = DefineGlobalClass("StandardError", typeof(System.SystemException), 0x00000003, def43, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def35 = Context.StandardErrorClass = DefineGlobalClass("StandardError", typeof(System.SystemException), 0x00000003, def44, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__StandardError)); - ExtendClass(typeof(System.Single), def38, LoadSystem__Single_Instance, LoadSystem__Single_Class, null, new IronRuby.Builtins.RubyModule[] {def39}, + ExtendClass(typeof(System.Single), def39, LoadSystem__Single_Instance, LoadSystem__Single_Class, null, new IronRuby.Builtins.RubyModule[] {def40}, new System.Func(IronRuby.Builtins.SingleOps.Create) ); - DefineGlobalClass("SystemExit", typeof(IronRuby.Builtins.SystemExit), 0x00000003, def43, LoadSystemExit_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("SystemExit", typeof(IronRuby.Builtins.SystemExit), 0x00000003, def44, LoadSystemExit_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.SystemExitOps.Factory), new System.Func(IronRuby.Builtins.SystemExitOps.Factory) ); - DefineGlobalClass("ArgumentError", typeof(System.ArgumentException), 0x00000003, def34, LoadArgumentError_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("ArgumentError", typeof(System.ArgumentException), 0x00000003, def35, LoadArgumentError_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__ArgumentError)); - DefineGlobalClass("Bignum", typeof(Microsoft.Scripting.Math.BigInteger), 0x00000003, def45, LoadBignum_Instance, LoadBignum_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); - DefineGlobalClass("EncodingError", typeof(IronRuby.Builtins.EncodingError), 0x00000003, def34, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("Bignum", typeof(Microsoft.Scripting.Math.BigInteger), 0x00000003, def46, LoadBignum_Instance, LoadBignum_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); + DefineGlobalClass("EncodingError", typeof(IronRuby.Builtins.EncodingError), 0x00000003, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__EncodingError)); - DefineGlobalClass("Fixnum", typeof(System.Int32), 0x00000003, def45, LoadFixnum_Instance, LoadFixnum_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); - DefineGlobalClass("IndexError", typeof(System.IndexOutOfRangeException), 0x00000003, def34, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("Fixnum", typeof(System.Int32), 0x00000003, def46, LoadFixnum_Instance, LoadFixnum_Class, null, IronRuby.Builtins.RubyModule.EmptyArray); + DefineGlobalClass("IndexError", typeof(System.IndexOutOfRangeException), 0x00000003, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__IndexError)); - DefineGlobalClass("Interrupt", typeof(IronRuby.Builtins.Interrupt), 0x00000103, def40, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("Interrupt", typeof(IronRuby.Builtins.Interrupt), 0x00000103, def41, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__Interrupt)); - IronRuby.Builtins.RubyClass def35 = DefineGlobalClass("IOError", typeof(System.IO.IOException), 0x00000003, def34, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def36 = DefineGlobalClass("IOError", typeof(System.IO.IOException), 0x00000003, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__IOError)); - DefineGlobalClass("LoadError", typeof(IronRuby.Builtins.LoadError), 0x00000003, def41, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("LoadError", typeof(IronRuby.Builtins.LoadError), 0x00000003, def42, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__LoadError)); - DefineGlobalClass("LocalJumpError", typeof(IronRuby.Builtins.LocalJumpError), 0x00000003, def34, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("LocalJumpError", typeof(IronRuby.Builtins.LocalJumpError), 0x00000003, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__LocalJumpError)); - IronRuby.Builtins.RubyClass def46 = DefineGlobalClass("NameError", typeof(System.MemberAccessException), 0x00000003, def34, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def47 = DefineGlobalClass("NameError", typeof(System.MemberAccessException), 0x00000003, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__NameError)); - DefineGlobalClass("NotImplementedError", typeof(IronRuby.Builtins.NotImplementedError), 0x00000003, def41, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("NotImplementedError", typeof(IronRuby.Builtins.NotImplementedError), 0x00000003, def42, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__NotImplementedError)); - IronRuby.Builtins.RubyClass def37 = DefineGlobalClass("RangeError", typeof(System.ArgumentOutOfRangeException), 0x00000003, def34, LoadRangeError_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def38 = DefineGlobalClass("RangeError", typeof(System.ArgumentOutOfRangeException), 0x00000003, def35, LoadRangeError_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__RangeError)); - DefineGlobalClass("RegexpError", typeof(IronRuby.Builtins.RegexpError), 0x00000003, def34, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("RegexpError", typeof(IronRuby.Builtins.RegexpError), 0x00000003, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__RegexpError)); - DefineGlobalClass("RuntimeError", typeof(IronRuby.Builtins.RuntimeError), 0x00000103, def34, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("RuntimeError", typeof(IronRuby.Builtins.RuntimeError), 0x00000103, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__RuntimeError)); - DefineGlobalClass("SecurityError", typeof(System.Security.SecurityException), 0x00000003, def34, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("SecurityError", typeof(System.Security.SecurityException), 0x00000003, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__SecurityError)); - DefineGlobalClass("SyntaxError", typeof(IronRuby.Builtins.SyntaxError), 0x00000003, def41, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("SyntaxError", typeof(IronRuby.Builtins.SyntaxError), 0x00000003, def42, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__SyntaxError)); - ExtendClass(typeof(System.Byte), def45, LoadSystem__Byte_Instance, LoadSystem__Byte_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, + ExtendClass(typeof(System.Byte), def46, LoadSystem__Byte_Instance, LoadSystem__Byte_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.ByteOps.InducedFrom), new System.Func(IronRuby.Builtins.ByteOps.InducedFrom), new System.Func(IronRuby.Builtins.ByteOps.InducedFrom) ); - ExtendClass(typeof(System.Int16), def45, LoadSystem__Int16_Instance, LoadSystem__Int16_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, + ExtendClass(typeof(System.Int16), def46, LoadSystem__Int16_Instance, LoadSystem__Int16_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.Int16Ops.InducedFrom), new System.Func(IronRuby.Builtins.Int16Ops.InducedFrom), new System.Func(IronRuby.Builtins.Int16Ops.InducedFrom) ); - ExtendClass(typeof(System.Int64), def45, LoadSystem__Int64_Instance, LoadSystem__Int64_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, + ExtendClass(typeof(System.Int64), def46, LoadSystem__Int64_Instance, LoadSystem__Int64_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.Int64Ops.InducedFrom), new System.Func(IronRuby.Builtins.Int64Ops.InducedFrom), new System.Func(IronRuby.Builtins.Int64Ops.InducedFrom) ); - ExtendClass(typeof(System.SByte), def45, LoadSystem__SByte_Instance, LoadSystem__SByte_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, + ExtendClass(typeof(System.SByte), def46, LoadSystem__SByte_Instance, LoadSystem__SByte_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.SByteOps.InducedFrom), new System.Func(IronRuby.Builtins.SByteOps.InducedFrom), new System.Func(IronRuby.Builtins.SByteOps.InducedFrom) ); - ExtendClass(typeof(System.UInt16), def45, LoadSystem__UInt16_Instance, LoadSystem__UInt16_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, + ExtendClass(typeof(System.UInt16), def46, LoadSystem__UInt16_Instance, LoadSystem__UInt16_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.UInt16Ops.InducedFrom), new System.Func(IronRuby.Builtins.UInt16Ops.InducedFrom), new System.Func(IronRuby.Builtins.UInt16Ops.InducedFrom) ); - ExtendClass(typeof(System.UInt32), def45, LoadSystem__UInt32_Instance, LoadSystem__UInt32_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, + ExtendClass(typeof(System.UInt32), def46, LoadSystem__UInt32_Instance, LoadSystem__UInt32_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.UInt32Ops.InducedFrom), new System.Func(IronRuby.Builtins.UInt32Ops.InducedFrom), new System.Func(IronRuby.Builtins.UInt32Ops.InducedFrom) ); - ExtendClass(typeof(System.UInt64), def45, LoadSystem__UInt64_Instance, LoadSystem__UInt64_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, + ExtendClass(typeof(System.UInt64), def46, LoadSystem__UInt64_Instance, LoadSystem__UInt64_Class, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.UInt64Ops.InducedFrom), new System.Func(IronRuby.Builtins.UInt64Ops.InducedFrom), new System.Func(IronRuby.Builtins.UInt64Ops.InducedFrom) ); - IronRuby.Builtins.RubyClass def36 = DefineGlobalClass("SystemCallError", typeof(System.Runtime.InteropServices.ExternalException), 0x00000003, def34, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def37 = DefineGlobalClass("SystemCallError", typeof(System.Runtime.InteropServices.ExternalException), 0x00000003, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.SystemCallErrorOps.Factory), new System.Func(IronRuby.Builtins.SystemCallErrorOps.Factory) ); - DefineGlobalClass("SystemStackError", typeof(IronRuby.Builtins.SystemStackError), 0x00000003, def34, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("SystemStackError", typeof(IronRuby.Builtins.SystemStackError), 0x00000003, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__SystemStackError)); - DefineGlobalClass("ThreadError", typeof(IronRuby.Builtins.ThreadError), 0x00000103, def34, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("ThreadError", typeof(IronRuby.Builtins.ThreadError), 0x00000103, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__ThreadError)); - DefineGlobalClass("TypeError", typeof(System.InvalidOperationException), 0x00000003, def34, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("TypeError", typeof(System.InvalidOperationException), 0x00000003, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__TypeError)); - DefineGlobalClass("ZeroDivisionError", typeof(System.DivideByZeroException), 0x00000003, def34, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("ZeroDivisionError", typeof(System.DivideByZeroException), 0x00000003, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__ZeroDivisionError)); - DefineGlobalClass("EOFError", typeof(IronRuby.Builtins.EOFError), 0x00000103, def35, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("EOFError", typeof(IronRuby.Builtins.EOFError), 0x00000103, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__EOFError)); - IronRuby.Builtins.RubyClass def32 = DefineClass("Errno::EACCES", typeof(System.UnauthorizedAccessException), 0x00000003, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def33 = DefineClass("Errno::EACCES", typeof(System.UnauthorizedAccessException), 0x00000003, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.Errno.UnauthorizedAccessExceptionOps.Create) ); - IronRuby.Builtins.RubyClass def9 = DefineClass("Errno::EADDRINUSE", typeof(IronRuby.Builtins.Errno.AddressInUseError), 0x00000103, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - IronRuby.Builtins.RubyClass def10 = DefineClass("Errno::EBADF", typeof(IronRuby.Builtins.Errno.BadFileDescriptorError), 0x00000103, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - IronRuby.Builtins.RubyClass def11 = DefineClass("Errno::ECHILD", typeof(IronRuby.Builtins.Errno.ChildError), 0x00000103, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - IronRuby.Builtins.RubyClass def12 = DefineClass("Errno::ECONNABORTED", typeof(IronRuby.Builtins.Errno.ConnectionAbortError), 0x00000103, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - IronRuby.Builtins.RubyClass def13 = DefineClass("Errno::ECONNREFUSED", typeof(IronRuby.Builtins.Errno.ConnectionRefusedError), 0x00000103, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - IronRuby.Builtins.RubyClass def14 = DefineClass("Errno::ECONNRESET", typeof(IronRuby.Builtins.Errno.ConnectionResetError), 0x00000103, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - IronRuby.Builtins.RubyClass def15 = DefineClass("Errno::EDOM", typeof(IronRuby.Builtins.Errno.DomainError), 0x00000103, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - IronRuby.Builtins.RubyClass def19 = DefineClass("Errno::EEXIST", typeof(IronRuby.Builtins.ExistError), 0x00000003, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def9 = DefineClass("Errno::EADDRINUSE", typeof(IronRuby.Builtins.Errno.AddressInUseError), 0x00000103, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyClass def10 = DefineClass("Errno::EBADF", typeof(IronRuby.Builtins.Errno.BadFileDescriptorError), 0x00000103, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyClass def11 = DefineClass("Errno::ECHILD", typeof(IronRuby.Builtins.Errno.ChildError), 0x00000103, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyClass def12 = DefineClass("Errno::ECONNABORTED", typeof(IronRuby.Builtins.Errno.ConnectionAbortError), 0x00000103, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyClass def13 = DefineClass("Errno::ECONNREFUSED", typeof(IronRuby.Builtins.Errno.ConnectionRefusedError), 0x00000103, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyClass def14 = DefineClass("Errno::ECONNRESET", typeof(IronRuby.Builtins.Errno.ConnectionResetError), 0x00000103, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyClass def15 = DefineClass("Errno::EDOM", typeof(IronRuby.Builtins.Errno.DomainError), 0x00000103, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyClass def19 = DefineClass("Errno::EEXIST", typeof(IronRuby.Builtins.ExistError), 0x00000003, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.Errno.ExistErrorOps.Create) ); - IronRuby.Builtins.RubyClass def21 = DefineClass("Errno::EINVAL", typeof(IronRuby.Builtins.InvalidError), 0x00000003, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def21 = DefineClass("Errno::EINVAL", typeof(IronRuby.Builtins.InvalidError), 0x00000003, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.Errno.InvalidErrorOps.Create) ); - IronRuby.Builtins.RubyClass def30 = DefineClass("Errno::ENOENT", typeof(System.IO.FileNotFoundException), 0x00000003, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def31 = DefineClass("Errno::ENOENT", typeof(System.IO.FileNotFoundException), 0x00000003, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.Errno.FileNotFoundExceptionOps.Create) ); - IronRuby.Builtins.RubyClass def17 = DefineClass("Errno::ENOTCONN", typeof(IronRuby.Builtins.Errno.NotConnectedError), 0x00000103, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - IronRuby.Builtins.RubyClass def29 = DefineClass("Errno::ENOTDIR", typeof(System.IO.DirectoryNotFoundException), 0x00000003, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def17 = DefineClass("Errno::ENOTCONN", typeof(IronRuby.Builtins.Errno.NotConnectedError), 0x00000103, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyClass def30 = DefineClass("Errno::ENOTDIR", typeof(System.IO.DirectoryNotFoundException), 0x00000003, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(IronRuby.Builtins.Errno.DirectoryNotFoundExceptionOps.Create) ); - IronRuby.Builtins.RubyClass def18 = DefineClass("Errno::EPIPE", typeof(IronRuby.Builtins.Errno.PipeError), 0x00000103, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - IronRuby.Builtins.RubyClass def16 = DefineClass("Errno::EXDEV", typeof(IronRuby.Builtins.Errno.ImproperLinkError), 0x00000103, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - DefineGlobalClass("ESPIPE", typeof(IronRuby.Builtins.InvalidSeekError), 0x00000103, def36, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); - DefineGlobalClass("FloatDomainError", typeof(IronRuby.Builtins.FloatDomainError), 0x00000103, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + IronRuby.Builtins.RubyClass def18 = DefineClass("Errno::EPIPE", typeof(IronRuby.Builtins.Errno.PipeError), 0x00000103, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + IronRuby.Builtins.RubyClass def16 = DefineClass("Errno::EXDEV", typeof(IronRuby.Builtins.Errno.ImproperLinkError), 0x00000103, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + DefineGlobalClass("ESPIPE", typeof(IronRuby.Builtins.InvalidSeekError), 0x00000103, def37, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray); + DefineGlobalClass("FloatDomainError", typeof(IronRuby.Builtins.FloatDomainError), 0x00000103, def38, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__FloatDomainError)); - DefineGlobalClass("NoMethodError", typeof(System.MissingMethodException), 0x00000003, def46, LoadNoMethodError_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray, + DefineGlobalClass("NoMethodError", typeof(System.MissingMethodException), 0x00000003, def47, LoadNoMethodError_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray, new System.Func(BuiltinsLibraryInitializer.ExceptionFactory__NoMethodError)); def24.SetBuiltinConstant("Constants", def25); def22.SetBuiltinConstant("Clr", def2); @@ -308,13 +309,14 @@ public sealed class BuiltinsLibraryInitializer : IronRuby.Builtins.LibraryInitia #endif Context.ObjectClass.SetBuiltinConstant("ENV", def7); #if !SILVERLIGHT - def24.SetBuiltinConstant("Stat", def31); + def24.SetBuiltinConstant("Stat", def32); #endif def2.SetBuiltinConstant("Name", def28); + def2.SetBuiltinConstant("Scope", def29); #if !SILVERLIGHT && !SILVERLIGHT def26.SetBuiltinConstant("Status", def27); #endif - def8.SetBuiltinConstant("EACCES", def32); + def8.SetBuiltinConstant("EACCES", def33); def8.SetBuiltinConstant("EADDRINUSE", def9); def8.SetBuiltinConstant("EBADF", def10); def8.SetBuiltinConstant("ECHILD", def11); @@ -324,9 +326,9 @@ public sealed class BuiltinsLibraryInitializer : IronRuby.Builtins.LibraryInitia def8.SetBuiltinConstant("EDOM", def15); def8.SetBuiltinConstant("EEXIST", def19); def8.SetBuiltinConstant("EINVAL", def21); - def8.SetBuiltinConstant("ENOENT", def30); + def8.SetBuiltinConstant("ENOENT", def31); def8.SetBuiltinConstant("ENOTCONN", def17); - def8.SetBuiltinConstant("ENOTDIR", def29); + def8.SetBuiltinConstant("ENOTDIR", def30); def8.SetBuiltinConstant("EPIPE", def18); def8.SetBuiltinConstant("EXDEV", def16); } @@ -1859,8 +1861,28 @@ public sealed class BuiltinsLibraryInitializer : IronRuby.Builtins.LibraryInitia } private static void LoadIronRuby_Class(IronRuby.Builtins.RubyModule/*!*/ module) { - module.DefineLibraryMethod("dlr_config", 0x61, - new System.Func(IronRuby.Builtins.IronRubyOps.GetCurrentRuntimeConfiguration) + module.DefineLibraryMethod("configuration", 0x61, + new System.Func(IronRuby.Builtins.IronRubyOps.GetConfiguration) + ); + + module.DefineLibraryMethod("globals", 0x61, + new System.Func(IronRuby.Builtins.IronRubyOps.GetGlobalScope) + ); + + module.DefineLibraryMethod("load", 0x61, + new System.Func(IronRuby.Builtins.IronRubyOps.Load) + ); + + module.DefineLibraryMethod("loaded_assemblies", 0x61, + new System.Func(IronRuby.Builtins.IronRubyOps.GetLoadedAssemblies) + ); + + module.DefineLibraryMethod("loaded_scripts", 0x61, + new System.Func>(IronRuby.Builtins.IronRubyOps.GetLoadedScripts) + ); + + module.DefineLibraryMethod("require", 0x61, + new System.Func(IronRuby.Builtins.IronRubyOps.Require) ); } @@ -2417,6 +2439,32 @@ public sealed class BuiltinsLibraryInitializer : IronRuby.Builtins.LibraryInitia } + private static void LoadIronRuby__Clr__Name_Class(IronRuby.Builtins.RubyModule/*!*/ module) { + module.DefineLibraryMethod("clr_to_ruby", 0x61, + new System.Func(IronRuby.Builtins.ClrNameOps.Mangle) + ); + + module.DefineLibraryMethod("mangle", 0x61, + new System.Func(IronRuby.Builtins.ClrNameOps.Mangle) + ); + + module.DefineLibraryMethod("ruby_to_clr", 0x61, + new System.Func(IronRuby.Builtins.ClrNameOps.Unmangle) + ); + + module.DefineLibraryMethod("unmangle", 0x61, + new System.Func(IronRuby.Builtins.ClrNameOps.Unmangle) + ); + + } + + private static void LoadIronRuby__Clr__Scope_Instance(IronRuby.Builtins.RubyModule/*!*/ module) { + module.DefineLibraryMethod("method_missing", 0x52, + new System.Func(IronRuby.Builtins.ScopeOps.MethodMissing) + ); + + } + private static void LoadIronRuby__Clr__String_Instance(IronRuby.Builtins.RubyModule/*!*/ module) { module.DefineLibraryMethod("%", 0x51, new System.Func(IronRuby.Builtins.ClrString.Format) diff --git a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/IronRuby.Libraries.Build.csproj b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/IronRuby.Libraries.Build.csproj index 1010abd047c9a889db243787a7aa50ce4594156d..f34e69238a8cdff8bf867bbf52218e39d6af083d 100644 GIT binary patch delta 22 ecmZ3sfU$2O;|3NJ=46Ka$@fi?H#3>2$N&Ic7zbwn delta 14 VcmeBM$hd3);|3O!%{eAYG5{)d1n~d> diff --git a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/IronRuby.Libraries.csproj b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/IronRuby.Libraries.csproj index 6e006de36c..d178a1f57e 100644 --- a/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/IronRuby.Libraries.csproj +++ b/Merlin/Main/Languages/Ruby/Libraries.LCA_RESTRICTED/IronRuby.Libraries.csproj @@ -2,7 +2,7 @@ Debug AnyCPU - 9.0.21022 + 9.0.30729 2.0 {77323B06-15A2-4CF4-8A7A-86EAA2B66498} Library @@ -132,6 +132,7 @@ + diff --git a/Merlin/Main/Languages/Ruby/Ruby.sln b/Merlin/Main/Languages/Ruby/Ruby.sln index 0f5e3c82fb..f8c76f32cb 100644 --- a/Merlin/Main/Languages/Ruby/Ruby.sln +++ b/Merlin/Main/Languages/Ruby/Ruby.sln @@ -17,28 +17,24 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IronRuby.Libraries", "Libra EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Scripting", "..\..\Runtime\Microsoft.Scripting\Microsoft.Scripting.csproj", "{EB66B766-6354-4208-A3D4-AACBDCB5C3B3}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IronRuby.Libraries.Yaml", "..\..\..\External.LCA_RESTRICTED\Languages\IronRuby\Yaml\IronRuby.Libraries.Yaml\IronRuby.Libraries.Yaml.csproj", "{AA18A245-E342-4368-A474-83178311A742}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IronRuby.Libraries.Yaml", "..\..\..\External.LCA_RESTRICTED\Languages\IronRuby\yaml\IronRuby.Libraries.Yaml\IronRuby.Libraries.Yaml.csproj", "{AA18A245-E342-4368-A474-83178311A742}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Scripting.ExtensionAttribute", "..\..\..\..\ndp\fx\src\Core\Microsoft\Scripting\Microsoft.Scripting.ExtensionAttribute.csproj", "{8B0F1074-750E-4D64-BF23-A1E0F54261E5}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A6B6A5B5-335A-4515-8535-954DE8A953EF}" ProjectSection(SolutionItems) = preProject Scripts\CodeGenerator.rb = Scripts\CodeGenerator.rb - RubyCodeCoverage.testrunconfig = RubyCodeCoverage.testrunconfig - RubyCodeCoverage.vsmdi = RubyCodeCoverage.vsmdi EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RubySpec", "Tests\RubySpec\RubySpec.csproj", "{534A82C6-3EB0-4888-ABD2-A15284683E8D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IronRuby.Tests.VS", "IronRuby.Tests.VS\IronRuby.Tests.VS.csproj", "{7FE874FB-A5C8-4EE6-A725-472CFA16BE7E}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ruby.ConsoleAny", "Console\Ruby.ConsoleAny.csproj", "{6EE7A428-D803-41BC-8248-1297C3ACE369}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Scripting.Debugging", "..\..\Debugging\Microsoft.Scripting.Debugging\Microsoft.Scripting.Debugging.csproj", "{ED82A346-1CD9-4CB0-9C00-4CDD4CF577CF}" EndProject Global GlobalSection(TeamFoundationVersionControl) = preSolution - SccNumberOfProjects = 15 + SccNumberOfProjects = 14 SccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C} SccTeamFoundationServer = http://vstfdevdiv:8080/ SccLocalPath0 = . @@ -75,18 +71,12 @@ Global SccProjectUniqueName11 = ..\\..\\..\\..\\ndp\\fx\\src\\Dynamic\\System\\Dynamic\\Microsoft.Dynamic.csproj SccProjectName11 = ../../../../ndp/fx/src/Dynamic/System/Dynamic SccLocalPath11 = ..\\..\\..\\..\\ndp\\fx\\src\\Dynamic\\System\\Dynamic - SccProjectUniqueName12 = IronRuby.Tests.VS\\IronRuby.Tests.VS.csproj - SccProjectName12 = IronRuby.Tests.VS - SccLocalPath12 = IronRuby.Tests.VS - SccProjectUniqueName13 = Console\\Ruby.ConsoleAny.csproj - SccProjectName13 = Console - SccLocalPath13 = Console - SccProjectUniqueName14 = ..\\..\\Debugging\\Microsoft.Scripting.Debugging\\Microsoft.Scripting.Debugging.csproj - SccProjectName14 = ../../Debugging/Microsoft.Scripting.Debugging - SccLocalPath14 = ..\\..\\Debugging\\Microsoft.Scripting.Debugging - EndGlobalSection - GlobalSection(TestCaseManagementSettings) = postSolution - CategoryFile = RubyCodeCoverage.vsmdi + SccProjectUniqueName12 = Console\\Ruby.ConsoleAny.csproj + SccProjectName12 = Console + SccLocalPath12 = Console + SccProjectUniqueName13 = ..\\..\\Debugging\\Microsoft.Scripting.Debugging\\Microsoft.Scripting.Debugging.csproj + SccProjectName13 = ../../Debugging/Microsoft.Scripting.Debugging + SccLocalPath13 = ..\\..\\Debugging\\Microsoft.Scripting.Debugging EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -191,14 +181,6 @@ Global {534A82C6-3EB0-4888-ABD2-A15284683E8D}.Release|Any CPU.ActiveCfg = Release|Any CPU {534A82C6-3EB0-4888-ABD2-A15284683E8D}.Silverlight Debug|Any CPU.ActiveCfg = Debug|Any CPU {534A82C6-3EB0-4888-ABD2-A15284683E8D}.Silverlight Release|Any CPU.ActiveCfg = Release|Any CPU - {7FE874FB-A5C8-4EE6-A725-472CFA16BE7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7FE874FB-A5C8-4EE6-A725-472CFA16BE7E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7FE874FB-A5C8-4EE6-A725-472CFA16BE7E}.FxCop|Any CPU.ActiveCfg = Release|Any CPU - {7FE874FB-A5C8-4EE6-A725-472CFA16BE7E}.FxCop|Any CPU.Build.0 = Release|Any CPU - {7FE874FB-A5C8-4EE6-A725-472CFA16BE7E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7FE874FB-A5C8-4EE6-A725-472CFA16BE7E}.Release|Any CPU.Build.0 = Release|Any CPU - {7FE874FB-A5C8-4EE6-A725-472CFA16BE7E}.Silverlight Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7FE874FB-A5C8-4EE6-A725-472CFA16BE7E}.Silverlight Release|Any CPU.ActiveCfg = Release|Any CPU {6EE7A428-D803-41BC-8248-1297C3ACE369}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6EE7A428-D803-41BC-8248-1297C3ACE369}.Debug|Any CPU.Build.0 = Debug|Any CPU {6EE7A428-D803-41BC-8248-1297C3ACE369}.FxCop|Any CPU.ActiveCfg = Release|Any CPU diff --git a/Merlin/Main/Languages/Ruby/Ruby/Builtins/RubyClass.cs b/Merlin/Main/Languages/Ruby/Ruby/Builtins/RubyClass.cs index 0447e1b64b..7abec225a3 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Builtins/RubyClass.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Builtins/RubyClass.cs @@ -35,11 +35,6 @@ namespace IronRuby.Builtins { public sealed partial class RubyClass : RubyModule, IDuplicable { - /// - /// Visibility context within which all methods are visible. - /// - public const RubyClass IgnoreVisibility = null; - public const string/*!*/ ClassSingletonName = "__ClassSingleton"; public const string/*!*/ ClassSingletonSingletonName = "__ClassSingletonSingleton"; public const string/*!*/ MainSingletonName = "__MainSingleton"; @@ -641,7 +636,7 @@ public RubyClass(RubyClass/*!*/ rubyClass) internal RubyMemberInfo ResolveMethodMissingForSite(string/*!*/ name, RubyMethodVisibility incompatibleVisibility) { Context.RequiresClassHierarchyLock(); - var methodMissing = ResolveMethodForSiteNoLock(Symbols.MethodMissing, null); + var methodMissing = ResolveMethodForSiteNoLock(Symbols.MethodMissing, VisibilityContext.AllVisible); if (incompatibleVisibility == RubyMethodVisibility.None) { methodMissing.InvalidateSitesOnMissingMethodAddition(name, Context); } @@ -1208,7 +1203,7 @@ private sealed class ClrOverloadInfo { // check version of the class so that we invalidate the rule whenever the initializer changes: metaBuilder.AddVersionTest(this); - initializer = ResolveMethodForSiteNoLock(Symbols.Initialize, IgnoreVisibility).Info; + initializer = ResolveMethodForSiteNoLock(Symbols.Initialize, VisibilityContext.AllVisible).Info; // Initializer resolves to Object#initializer unless overridden in a derived class. // We ensure that this method cannot be removed. diff --git a/Merlin/Main/Languages/Ruby/Ruby/Builtins/RubyEncoding.cs b/Merlin/Main/Languages/Ruby/Ruby/Builtins/RubyEncoding.cs index ae2cf40ef9..3487d96e67 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Builtins/RubyEncoding.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Builtins/RubyEncoding.cs @@ -382,7 +382,7 @@ public class RubyEncoding : IExpressionSerializable { ContractUtils.RequiresNotNull(encoding, "encoding"); if (encoding == BinaryEncoding.Instance) { return Binary; - } else if (encoding.ToString() == Encoding.UTF8.ToString()) { + } else if (encoding.ToString() == Encoding.UTF8.ToString()) { return UTF8; } else { throw new ArgumentException(String.Format("Unknown encoding: '{0}'", encoding)); diff --git a/Merlin/Main/Languages/Ruby/Ruby/Builtins/RubyModule.cs b/Merlin/Main/Languages/Ruby/Ruby/Builtins/RubyModule.cs index 866fa06958..602bd8dfff 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Builtins/RubyModule.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Builtins/RubyModule.cs @@ -1215,7 +1215,7 @@ private enum ConstantLookupResult { RubyMemberInfo method; using (Context.ClassHierarchyLocker()) { // MRI: aliases a super-forwarder not the real method. - method = ResolveMethodNoLock(oldName, RubyClass.IgnoreVisibility, MethodLookup.FallbackToObject | MethodLookup.ReturnForwarder).Info; + method = ResolveMethodNoLock(oldName, VisibilityContext.AllVisible, MethodLookup.FallbackToObject | MethodLookup.ReturnForwarder).Info; if (method == null) { throw RubyExceptions.CreateUndefinedMethodError(this, oldName); } @@ -1496,32 +1496,32 @@ private enum ConstantLookupResult { } // thread-safe: - public MethodResolutionResult ResolveMethodForSite(string/*!*/ name, RubyClass visibilityContext) { + public MethodResolutionResult ResolveMethodForSite(string/*!*/ name, VisibilityContext visibility) { using (Context.ClassHierarchyLocker()) { - return ResolveMethodForSiteNoLock(name, visibilityContext); + return ResolveMethodForSiteNoLock(name, visibility); } } // thread-safe: - public MethodResolutionResult ResolveMethod(string/*!*/ name, RubyClass visibilityContext) { + public MethodResolutionResult ResolveMethod(string/*!*/ name, VisibilityContext visibility) { using (Context.ClassHierarchyLocker()) { - return ResolveMethodNoLock(name, visibilityContext); + return ResolveMethodNoLock(name, visibility); } } - public MethodResolutionResult ResolveMethodForSiteNoLock(string/*!*/ name, RubyClass visibilityContext) { - return ResolveMethodForSiteNoLock(name, visibilityContext, MethodLookup.Default); + public MethodResolutionResult ResolveMethodForSiteNoLock(string/*!*/ name, VisibilityContext visibility) { + return ResolveMethodForSiteNoLock(name, visibility, MethodLookup.Default); } - internal MethodResolutionResult ResolveMethodForSiteNoLock(string/*!*/ name, RubyClass visibilityContext, MethodLookup options) { - return ResolveMethodNoLock(name, visibilityContext, options).InvalidateSitesOnOverride(); + internal MethodResolutionResult ResolveMethodForSiteNoLock(string/*!*/ name, VisibilityContext visibility, MethodLookup options) { + return ResolveMethodNoLock(name, visibility, options).InvalidateSitesOnOverride(); } - public MethodResolutionResult ResolveMethodNoLock(string/*!*/ name, RubyClass visibilityContext) { - return ResolveMethodNoLock(name, visibilityContext, MethodLookup.Default); + public MethodResolutionResult ResolveMethodNoLock(string/*!*/ name, VisibilityContext visibility) { + return ResolveMethodNoLock(name, visibility, MethodLookup.Default); } - public MethodResolutionResult ResolveMethodNoLock(string/*!*/ name, RubyClass visibilityContext, MethodLookup options) { + public MethodResolutionResult ResolveMethodNoLock(string/*!*/ name, VisibilityContext visibility, MethodLookup options) { Context.RequiresClassHierarchyLock(); Assert.NotNull(name); @@ -1534,12 +1534,12 @@ private enum ConstantLookupResult { if (ForEachAncestor((module) => { owner = module; - foundCallerSelf |= module == visibilityContext; + foundCallerSelf |= module == visibility.Class; return module.TryGetMethod(name, ref skipHidden, (options & MethodLookup.Virtual) != 0, out info); })) { if (info == null || info.IsUndefined) { result = MethodResolutionResult.NotFound; - } else if (!IsMethodVisible(info, owner, visibilityContext, foundCallerSelf)) { + } else if (!IsMethodVisible(info, owner, visibility, foundCallerSelf)) { result = new MethodResolutionResult(info, owner, false); } else if (info.IsSuperForwarder) { if ((options & MethodLookup.ReturnForwarder) != 0) { @@ -1557,16 +1557,18 @@ private enum ConstantLookupResult { // Note: all classes include Object in ancestors, so we don't need to search it again: if (!result.Found && (options & MethodLookup.FallbackToObject) != 0 && !IsClass) { - return _context.ObjectClass.ResolveMethodNoLock(name, visibilityContext, options & ~MethodLookup.FallbackToObject); + return _context.ObjectClass.ResolveMethodNoLock(name, visibility, options & ~MethodLookup.FallbackToObject); } return result; } - private bool IsMethodVisible(RubyMemberInfo/*!*/ method, RubyModule/*!*/ owner, RubyClass visibilityContext, bool foundCallerSelf) { - // call with implicit self => all methods are visible - if (visibilityContext == RubyClass.IgnoreVisibility) { - return true; + private bool IsMethodVisible(RubyMemberInfo/*!*/ method, RubyModule/*!*/ owner, VisibilityContext visibility, bool foundCallerSelf) { + // Visibility not constrained by a class: + // - call with implicit self => all methods are visible. + // - interop call => only public methods are visible. + if (visibility.Class == null) { + return visibility.IsVisible(method.Visibility); } if (method.Visibility == RubyMethodVisibility.Protected) { @@ -1576,7 +1578,7 @@ private enum ConstantLookupResult { } // walk ancestors from caller's self class (visibilityContext) // until the method owner is found or this module is found (this module is a descendant of the owner): - return visibilityContext.ForEachAncestor((module) => module == owner || module == this); + return visibility.Class.ForEachAncestor((module) => module == owner || module == this); } return method.Visibility == RubyMethodVisibility.Public; @@ -1639,7 +1641,7 @@ private enum ConstantLookupResult { if (virtualLookup) { string mangled; - if ((mangled = RubyUtils.MangleName(name)) != name && TryGetDefinedMethod(mangled, ref skipHidden, out method) + if ((mangled = RubyUtils.TryMangleName(name)) != null && TryGetDefinedMethod(mangled, ref skipHidden, out method) && method.IsRubyMember) { return true; } diff --git a/Merlin/Main/Languages/Ruby/Ruby/Compiler/Parser/Parser.cs b/Merlin/Main/Languages/Ruby/Ruby/Compiler/Parser/Parser.cs index 00a3bbc397..c3b45ca717 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Compiler/Parser/Parser.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Compiler/Parser/Parser.cs @@ -508,7 +508,7 @@ public Parser() public static string/*!*/ TerminalToString(int terminal) { Debug.Assert(terminal >= 0); if (((Tokens)terminal).ToString() != terminal.ToString()) { - return IronRuby.Runtime.RubyUtils.MangleName(((Tokens)terminal).ToString()).ToUpper(); + return IronRuby.Runtime.RubyUtils.TryMangleName(((Tokens)terminal).ToString()).ToUpper(); } else { return CharToString((char)terminal); } diff --git a/Merlin/Main/Languages/Ruby/Ruby/Ruby.Build.csproj b/Merlin/Main/Languages/Ruby/Ruby/Ruby.Build.csproj index c6bc630c979625910fed8ccfc3410a999e14aa53..bce274f9953a729dd340a954bd4e18c36c3276b0 100644 GIT binary patch delta 51 zcmZ2+i)qDerVYOqPyR5;MKFvZlc5-hlYlq}h)X6f?9iTkz+%QEJ)_AEwS1c|EeYcQ E04RYJQ2+n{ delta 25 hcmZ2+n`y-@rVYOqPd;EVW0IcHWQSV5%|T1UH~_193(^1p diff --git a/Merlin/Main/Languages/Ruby/Ruby/Ruby.csproj b/Merlin/Main/Languages/Ruby/Ruby/Ruby.csproj index f0a26fd35e..f7df997fe8 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Ruby.csproj +++ b/Merlin/Main/Languages/Ruby/Ruby/Ruby.csproj @@ -2,7 +2,7 @@ Debug AnyCPU - 9.0.21022 + 9.0.30729 2.0 {7F6984B4-EE6D-4E6F-ABB1-E210D7DC4FDD} Library @@ -192,6 +192,7 @@ + diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/ConvertToSAction.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/ConvertToSAction.cs index 4acf67a546..1a6cb6c5bd 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/ConvertToSAction.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/ConvertToSAction.cs @@ -78,7 +78,7 @@ public sealed class ConvertToSAction : RubyConversionAction { new[] { ToS, Symbols.MethodMissing } ); - conversionMethod = targetClass.ResolveMethodForSiteNoLock(ToS, RubyClass.IgnoreVisibility).Info; + conversionMethod = targetClass.ResolveMethodForSiteNoLock(ToS, VisibilityContext.AllVisible).Info; // find method_missing - we need to add "to_xxx" methods to the missing methods table: if (conversionMethod == null) { diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/InteropBinder.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/InteropBinder.cs index be888ebd55..32276e9eb9 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/InteropBinder.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/InteropBinder.cs @@ -248,7 +248,7 @@ internal InvokeMember(RubyContext/*!*/ context, string/*!*/ name, CallInfo/*!*/ Func/*!*/ fallback) { Debug.Assert(fallback != null); - var callArgs = new CallArguments(context, target, args, RubyCallSignature.WithImplicitSelf(callInfo.ArgumentCount)); + var callArgs = new CallArguments(context, target, args, RubyCallSignature.Interop(callInfo.ArgumentCount)); var metaBuilder = new MetaObjectBuilder(target, args); if (!RubyCallAction.BuildCall(metaBuilder, methodName, callArgs, false, false)) { @@ -301,7 +301,7 @@ internal GetMember(RubyContext/*!*/ context, string/*!*/ name) Func/*!*/ fallback) { Debug.Assert(fallback != null); - var callArgs = new CallArguments(context, target, DynamicMetaObject.EmptyMetaObjects, RubyCallSignature.WithImplicitSelf(0)); + var callArgs = new CallArguments(context, target, DynamicMetaObject.EmptyMetaObjects, RubyCallSignature.Interop(0)); var metaBuilder = new MetaObjectBuilder(target); if (!RubyCallAction.BuildAccess(metaBuilder, binder.Name, callArgs, false, false)) { @@ -357,7 +357,7 @@ internal SetMember(RubyContext/*!*/ context, string/*!*/ name) Debug.Assert(fallback != null); var args = new[] { value }; - var callArgs = new CallArguments(context, target, args, RubyCallSignature.WithImplicitSelf(1)); + var callArgs = new CallArguments(context, target, args, RubyCallSignature.Interop(1)); var metaBuilder = new MetaObjectBuilder(target, args); if (!RubyCallAction.BuildCall(metaBuilder, binder.Name + "=", callArgs, false, false)) { @@ -414,7 +414,7 @@ internal GetIndex(RubyContext/*!*/ context, CallInfo/*!*/ callInfo) Func/*!*/ fallback) { Debug.Assert(fallback != null); - var callArgs = new CallArguments(context, target, indexes, RubyCallSignature.WithImplicitSelf(indexes.Length)); + var callArgs = new CallArguments(context, target, indexes, RubyCallSignature.Interop(indexes.Length)); var metaBuilder = new MetaObjectBuilder(target, indexes); if (!RubyCallAction.BuildCall(metaBuilder, "[]", callArgs, false, false)) { @@ -472,7 +472,7 @@ internal SetIndex(RubyContext/*!*/ context, CallInfo/*!*/ callInfo) var args = ArrayUtils.Append(indexes, value); var callArgs = new CallArguments(context, target, args, - new RubyCallSignature(indexes.Length, RubyCallFlags.HasImplicitSelf | RubyCallFlags.HasRhsArgument) + new RubyCallSignature(indexes.Length, RubyCallFlags.IsInteropCall | RubyCallFlags.HasRhsArgument) ); var metaBuilder = new MetaObjectBuilder(target, args); diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/MetaObjectBuilder.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/MetaObjectBuilder.cs index 4393d91bd0..f2b0c37341 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/MetaObjectBuilder.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/MetaObjectBuilder.cs @@ -27,6 +27,7 @@ using Ast = System.Linq.Expressions.Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; using System.Collections; +using Microsoft.Scripting.Generation; namespace IronRuby.Runtime.Calls { public sealed class MetaObjectBuilder { @@ -210,10 +211,37 @@ internal MetaObjectBuilder(DynamicMetaObject target, params DynamicMetaObject/*! if (value == null) { return Ast.Equal(expression, AstUtils.Constant(null)); } else { - return RuleBuilder.MakeTypeTestExpression(value.GetType(), expression); + return MakeTypeTestExpression(value.GetType(), expression); } } + public static Expression MakeTypeTestExpression(Type t, Expression expr) { + // we must always check for non-sealed types explicitly - otherwise we end up + // doing fast-path behavior on a subtype which overrides behavior that wasn't + // present for the base type. + //TODO there's a question about nulls here + if (CompilerHelpers.IsSealed(t) && t == expr.Type) { + if (t.IsValueType) { + return AstUtils.Constant(true); + } + return Ast.NotEqual(expr, AstUtils.Constant(null)); + } + + return Ast.AndAlso( + Ast.NotEqual( + expr, + AstUtils.Constant(null)), + Ast.Equal( + Ast.Call( + AstUtils.Convert(expr, typeof(object)), + typeof(object).GetMethod("GetType") + ), + AstUtils.Constant(t) + ) + ); + } + + public void AddObjectTypeCondition(object value, Expression/*!*/ expression) { AddCondition(GetObjectTypeTestExpression(value, expression)); } diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/ProtocolConversionAction.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/ProtocolConversionAction.cs index 0dd5d89dc1..9d096aef98 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/ProtocolConversionAction.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/ProtocolConversionAction.cs @@ -193,20 +193,20 @@ public abstract class ProtocolConversionAction : RubyConversionAction { ); // we can optimize if Kernel#respond_to? method is not overridden: - respondToMethod = targetClass.ResolveMethodForSiteNoLock(Symbols.RespondTo, RubyClass.IgnoreVisibility); + respondToMethod = targetClass.ResolveMethodForSiteNoLock(Symbols.RespondTo, VisibilityContext.AllVisible); if (respondToMethod.Found && respondToMethod.Info.DeclaringModule == targetClass.Context.KernelModule && respondToMethod.Info is RubyLibraryMethodInfo) { // TODO: better override detection respondToMethod = MethodResolutionResult.NotFound; // get the first applicable conversion: foreach (var conversion in conversions) { selectedConversion = conversion; - conversionMethod = targetClass.ResolveMethodForSiteNoLock(conversion.ToMethodName, RubyClass.IgnoreVisibility).Info; + conversionMethod = targetClass.ResolveMethodForSiteNoLock(conversion.ToMethodName, VisibilityContext.AllVisible).Info; if (conversionMethod != null) { break; } else { // find method_missing - we need to add "to_xxx" methods to the missing methods table: if (!methodMissing.Found) { - methodMissing = targetClass.ResolveMethodNoLock(Symbols.MethodMissing, RubyClass.IgnoreVisibility); + methodMissing = targetClass.ResolveMethodNoLock(Symbols.MethodMissing, VisibilityContext.AllVisible); } methodMissing.InvalidateSitesOnMissingMethodAddition(conversion.ToMethodName, targetClass.Context); } diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/RubyBinder.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/RubyBinder.cs index 869c51d16c..22bb43fcb4 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/RubyBinder.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/RubyBinder.cs @@ -41,7 +41,7 @@ internal RubyBinder(RubyContext/*!*/ context) #region Conversions - public override Expression ConvertExpression(Expression expr, Type toType, ConversionResultKind kind, Expression context) { + public override Expression ConvertExpression(Expression expr, Type toType, ConversionResultKind kind, OverloadResolverFactory context) { throw new InvalidOperationException("OBSOLETE"); } diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/RubyCallAction.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/RubyCallAction.cs index ee6a8491f5..820504a5be 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/RubyCallAction.cs @@ -187,23 +187,25 @@ internal protected RubyCallAction(RubyContext context, string/*!*/ methodName, R } } - private static RubyClass GetVisibilityContext(RubyCallSignature callSignature, RubyScope scope) { - // TODO: All sites should have either implicit-self or has-scope flag set? - return callSignature.HasImplicitSelf || !callSignature.HasScope ? RubyClass.IgnoreVisibility : scope.SelfImmediateClass; + private static VisibilityContext GetVisibilityContext(RubyCallSignature callSignature, RubyScope scope) { + return callSignature.HasImplicitSelf || !callSignature.HasScope ? + new VisibilityContext(callSignature.IsInteropCall ? RubyMethodAttributes.Public : RubyMethodAttributes.VisibilityMask) : + new VisibilityContext(scope.SelfImmediateClass); } internal static MethodResolutionResult Resolve(MetaObjectBuilder/*!*/ metaBuilder, string/*!*/ methodName, CallArguments/*!*/ args, out RubyMemberInfo methodMissing) { MethodResolutionResult method; - RubyClass targetClass = args.TargetClass; + var targetClass = args.TargetClass; + var visibilityContext = GetVisibilityContext(args.Signature, args.Scope); using (targetClass.Context.ClassHierarchyLocker()) { metaBuilder.AddTargetTypeTest(args.Target, targetClass, args.TargetExpression, args.MetaContext, new[] { methodName, Symbols.MethodMissing } ); var options = args.Signature.IsVirtualCall ? MethodLookup.Virtual : MethodLookup.Default; - method = targetClass.ResolveMethodForSiteNoLock(methodName, GetVisibilityContext(args.Signature, args.Scope), options); + method = targetClass.ResolveMethodForSiteNoLock(methodName, visibilityContext, options); if (!method.Found) { methodMissing = targetClass.ResolveMethodMissingForSite(methodName, method.IncompatibleVisibility); } else { @@ -212,12 +214,12 @@ internal protected RubyCallAction(RubyContext context, string/*!*/ methodName, R } // Whenever the current self's class changes we need to invalidate the rule, if a protected method is being called. - if (method.Info != null && method.Info.IsProtected && !args.Signature.HasImplicitSelf) { + if (method.Info != null && method.Info.IsProtected && visibilityContext.Class != null) { // We don't need to compare versions, just the class objects (super-class relationship cannot be changed). // Since we don't want to hold on a class object (to make it collectible) we compare references to the version handlers. metaBuilder.AddCondition(Ast.Equal( Methods.GetSelfClassVersionHandle.OpCall(AstUtils.Convert(args.MetaScope.Expression, typeof(RubyScope))), - Ast.Constant(args.Scope.SelfImmediateClass.Version) + Ast.Constant(visibilityContext.Class.Version) )); } diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/RubyCallSignature.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/RubyCallSignature.cs index aa305cdbc5..c39edcc7ae 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/RubyCallSignature.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/RubyCallSignature.cs @@ -35,16 +35,19 @@ public enum RubyCallFlags { // Used for private visibility check. By default method call sites have explicit self, so private methods are not visible. HasImplicitSelf = 16, + // Interop calls can only see Ruby-public members. + IsInteropCall = 32, + // If the resolved method is a Ruby method call it otherwise invoke #base# method on target's type. // Used in method overrides defined in types emitted for Ruby classes that derive from CLR type. - IsVirtualCall = 32, + IsVirtualCall = 64, } /// /// RubyScope/RubyContext, (self), (argument){ArgumentCount}, (splatted-argument)?, (block)? /// public struct RubyCallSignature : IEquatable { - private const int FlagsCount = 6; + private const int FlagsCount = 7; private const int MaxArgumentCount = (int)(UInt32.MaxValue >> FlagsCount); private const RubyCallFlags FlagsMask = (RubyCallFlags)(1 << FlagsCount) - 1; @@ -55,6 +58,7 @@ public struct RubyCallSignature : IEquatable { public bool HasBlock { get { return ((RubyCallFlags)_countAndFlags & RubyCallFlags.HasBlock) != 0; } } public bool HasSplattedArgument { get { return ((RubyCallFlags)_countAndFlags & RubyCallFlags.HasSplattedArgument) != 0; } } public bool HasRhsArgument { get { return ((RubyCallFlags)_countAndFlags & RubyCallFlags.HasRhsArgument) != 0; } } + public bool IsInteropCall { get { return ((RubyCallFlags)_countAndFlags & RubyCallFlags.IsInteropCall) != 0; } } public bool IsVirtualCall { get { return ((RubyCallFlags)_countAndFlags & RubyCallFlags.IsVirtualCall) != 0; } } public int ArgumentCount { get { return (int)_countAndFlags >> FlagsCount; } } @@ -97,7 +101,7 @@ public struct RubyCallSignature : IEquatable { } internal static bool TryCreate(CallInfo callInfo, out RubyCallSignature callSignature) { - callSignature = Simple(callInfo.ArgumentCount); + callSignature = RubyCallSignature.Interop(callInfo.ArgumentCount); return callInfo.ArgumentNames.Count != 0; } @@ -109,6 +113,10 @@ public struct RubyCallSignature : IEquatable { return new RubyCallSignature(argumentCount, RubyCallFlags.None); } + public static RubyCallSignature Interop(int argumentCount) { + return new RubyCallSignature(argumentCount, RubyCallFlags.IsInteropCall); + } + public static RubyCallSignature WithBlock(int argumentCount) { return new RubyCallSignature(argumentCount, RubyCallFlags.HasBlock); } diff --git a/Merlin/Main/Languages/Ruby/IronRuby.Tests.VS/MsTest.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/VisibilityContext.cs similarity index 50% rename from Merlin/Main/Languages/Ruby/IronRuby.Tests.VS/MsTest.cs rename to Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/VisibilityContext.cs index 6bbdeb8248..8b839d2017 100644 --- a/Merlin/Main/Languages/Ruby/IronRuby.Tests.VS/MsTest.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Calls/VisibilityContext.cs @@ -13,14 +13,27 @@ * * ***************************************************************************/ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using IronRuby.Builtins; -namespace IronRuby.Tests { - [TestClass] - public class MsTest { - [TestMethod] - public void Main() { - Driver.Main(new string[0]); +namespace IronRuby.Runtime.Calls { + public struct VisibilityContext { + public static readonly VisibilityContext AllVisible = new VisibilityContext(RubyMethodAttributes.VisibilityMask); + + public readonly RubyClass Class; + public readonly RubyMethodAttributes Visible; + + public VisibilityContext(RubyMethodAttributes mask) { + Class = null; + Visible = mask; + } + + public VisibilityContext(RubyClass cls) { + Class = cls; + Visible = RubyMethodAttributes.VisibilityMask; + } + + public bool IsVisible(RubyMethodVisibility visibility) { + return ((int)visibility & (int)Visible) != 0; } } } diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/ClrName.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/ClrName.cs index 79bd821932..157ebc2690 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/ClrName.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/ClrName.cs @@ -35,12 +35,16 @@ public class ClrName : IEquatable { public string/*!*/ MangledName { get { if (_mangled == null) { - _mangled = RubyUtils.MangleName(_actual); + _mangled = RubyUtils.TryMangleName(_actual) ?? _actual; } return _mangled; } } + public bool HasMangledName { + get { return !ReferenceEquals(_actual, MangledName); } + } + public ClrName(string/*!*/ actualName) { ContractUtils.RequiresNotNull(actualName, "actualName"); _actual = actualName; diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Key.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Key.cs index 8d8eab2b68..6b86159b61 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Key.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Key.cs @@ -26,6 +26,7 @@ public static class Key { } } + [Serializable] public class Key : IEquatable> { public readonly T0/*!*/ First; public readonly T1/*!*/ Second; @@ -57,6 +58,7 @@ public class Key : IEquatable> { } } + [Serializable] public sealed class Key : Key, IEquatable> { public readonly T2/*!*/ Third; diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Loader.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Loader.cs index 03014336c2..af0dfc8170 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Loader.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Loader.cs @@ -36,6 +36,7 @@ public enum LoadFlags { LoadOnce = 1, LoadIsolated = 2, AppendExtensions = 4, + ResolveLoaded = 8 } // TODO: thread safety @@ -58,7 +59,10 @@ internal enum FileKind { private readonly RubyArray/*!*/ _loadedFiles; // files that were required but their execution haven't completed yet: - private readonly Stack/*!*/ _unfinishedFiles; + private readonly Stack/*!*/ _unfinishedFiles; + + // lazy init + private SynchronizedDictionary _loadedScripts; // TODO: static // maps full normalized path to compiled code: @@ -97,6 +101,21 @@ private struct CompiledFile { get { return _loadedFiles; } } + /// + /// Contains all loaded foreign language scripts. Maps path to scope created for each loaded script. + /// A script is published here as soon as its scopr is created just before it is executed. + /// + public IDictionary/*!*/ LoadedScripts { + get { + if (_loadedScripts == null) { + Interlocked.CompareExchange(ref _loadedScripts, + new SynchronizedDictionary(new Dictionary(DomainManager.Platform.PathComparer)), null + ); + } + return _loadedScripts; + } + } + private PlatformAdaptationLayer/*!*/ Platform { get { return DomainManager.Platform; } } @@ -104,7 +123,7 @@ private struct CompiledFile { private ScriptDomainManager/*!*/ DomainManager { get { return _context.DomainManager; } } - + internal Loader(RubyContext/*!*/ context) { Assert.NotNull(context); _context = context; @@ -231,10 +250,19 @@ private struct CompiledFile { } } + public bool LoadFile(Scope globalScope, object self, MutableString/*!*/ path, LoadFlags flags) { + object loaded; + return LoadFile(globalScope, self, path, flags, out loaded); + } + /// /// Returns true if a Ruby file is successfully loaded, false if it is already loaded. /// - public bool LoadFile(Scope globalScope, object self, MutableString/*!*/ path, LoadFlags flags) { + /// + /// A scope against which the file should be executed or null to create a new scope. + /// + /// True if the file was loaded/executed by this call. + public bool LoadFile(Scope globalScope, object self, MutableString/*!*/ path, LoadFlags flags, out object loaded) { Assert.NotNull(path); string assemblyName, typeName; @@ -243,46 +271,69 @@ private struct CompiledFile { if (TryParseAssemblyName(strPath, out typeName, out assemblyName)) { if (AlreadyLoaded(path, flags)) { + loaded = ((flags & LoadFlags.ResolveLoaded) != 0) ? GetAssembly(assemblyName, true, false) : null; return false; } - if (LoadAssembly(assemblyName, typeName, false, false)) { + Assembly assembly = LoadAssembly(assemblyName, typeName, false, false); + if (assembly != null) { FileLoaded(path, flags); + loaded = assembly; return true; } } - return LoadFromPath(globalScope, self, strPath, flags); + return LoadFromPath(globalScope, self, strPath, flags, out loaded); } #region Assemblies + public Assembly LoadAssembly(string/*!*/ assemblyName, string typeName, bool throwOnError, bool tryPartialName) { + Assembly assembly = GetAssembly(assemblyName, throwOnError, tryPartialName); + return (assembly != null && LoadAssembly(assembly, typeName, throwOnError)) ? assembly : null; + } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadWithPartialName")] - public bool LoadAssembly(string/*!*/ assemblyName, string typeName, bool throwOnError, bool tryPartialName) { - Utils.Log(String.Format("Loading assembly '{0}' and type '{1}'", assemblyName, typeName), "LOADER"); - - Assembly assembly; - try { - try { - assembly = Platform.LoadAssembly(assemblyName); - } catch (FileNotFoundException) { + private Assembly GetAssembly(string/*!*/ assemblyName, bool throwOnError, bool tryPartialName) { #if SILVERLIGHT - throw; -#else - if (tryPartialName) { -#pragma warning disable 618,612 // csc, gmcs - assembly = Assembly.LoadWithPartialName(assemblyName); -#pragma warning restore 618,612 + tryPartialName = false; +#endif + try { + return Platform.LoadAssembly(assemblyName); + } catch (Exception e) { + if (!tryPartialName || !(e is FileNotFoundException)) { + if (throwOnError) { + throw new LoadError(e.Message, e); } else { - throw; + return null; } -#endif } - } catch (Exception e) { - if (throwOnError) throw new LoadError(e.Message, e); - return false; } +#if SILVERLIGHT + throw Assert.Unreachable; +#else +#pragma warning disable 618,612 // csc, gmcs + Assembly assembly; + try { + assembly = Assembly.LoadWithPartialName(assemblyName); + } catch (Exception e) { + if (throwOnError) { + throw new LoadError(e.Message, e); + } else { + return null; + } + } + if (assembly == null && throwOnError) { + throw new LoadError(String.Format("Assembly '{0}' not found", assemblyName)); + } +#pragma warning restore 618,612 + return assembly; +#endif + } + + private bool LoadAssembly(Assembly/*!*/ assembly, string typeName, bool throwOnError) { + Utils.Log(String.Format("Loading assembly '{0}' and type '{1}'", assembly, typeName), "LOADER"); Type initializerType; if (typeName != null) { // load Ruby library: @@ -411,7 +462,7 @@ private class ResolvedFile { } } - private bool LoadFromPath(Scope globalScope, object self, string/*!*/ path, LoadFlags flags) { + private bool LoadFromPath(Scope globalScope, object self, string/*!*/ path, LoadFlags flags, out object loaded) { Assert.NotNull(path); string[] sourceFileExtensions = DomainManager.Configuration.GetFileExtensions(); @@ -426,6 +477,20 @@ private class ResolvedFile { } if (AlreadyLoaded(pathWithExtension, flags) || _unfinishedFiles.Contains(pathWithExtension.ToString())) { + if ((flags & LoadFlags.ResolveLoaded) != 0) { + var fullPath = Platform.GetFullPath(file.Path); + if (file.SourceUnit != null) { + Scope loadedScope; + if (!LoadedScripts.TryGetValue(fullPath, out loadedScope)) { + throw new LoadError(String.Format("no such file to load -- {0}", file.Path)); + } + loaded = loadedScope; + } else { + loaded = Platform.LoadAssemblyFromPath(fullPath); + } + } else { + loaded = null; + } return false; } @@ -434,18 +499,19 @@ private class ResolvedFile { _unfinishedFiles.Push(pathWithExtension.ToString()); if (file.SourceUnit != null) { - - RubyContext rubySource = file.SourceUnit.LanguageContext as RubyContext; - if (rubySource != null) { - ExecuteRubySourceUnit(file.SourceUnit, globalScope, flags); + ScriptCode compiledCode; + if (file.SourceUnit.LanguageContext == _context) { + compiledCode = CompileRubySource(file.SourceUnit, flags); } else { - file.SourceUnit.Execute(); + compiledCode = file.SourceUnit.Compile(); } + loaded = Execute(globalScope, compiledCode); } else { Debug.Assert(file.Path != null); try { - Assembly asm = Platform.LoadAssemblyFromPath(Platform.GetFullPath(file.Path)); - DomainManager.LoadAssembly(asm); + Assembly assembly = Platform.LoadAssemblyFromPath(Platform.GetFullPath(file.Path)); + DomainManager.LoadAssembly(assembly); + loaded = assembly; } catch (Exception e) { throw new LoadError(e.Message, e); } @@ -459,7 +525,7 @@ private class ResolvedFile { return true; } - private void ExecuteRubySourceUnit(SourceUnit/*!*/ sourceUnit, Scope globalScope, LoadFlags flags) { + private ScriptCode/*!*/ CompileRubySource(SourceUnit/*!*/ sourceUnit, LoadFlags flags) { Assert.NotNull(sourceUnit); // TODO: check file timestamp @@ -467,11 +533,8 @@ private class ResolvedFile { CompiledFile compiledFile; if (TryGetCompiledFile(fullPath, out compiledFile)) { Utils.Log(String.Format("{0}: {1}", ++_cacheHitCount, sourceUnit.Path), "LOAD_CACHED"); - if (globalScope != null) { - compiledFile.CompiledCode.Run(globalScope); - } else { - compiledFile.CompiledCode.Run(); - } + + return compiledFile.CompiledCode; } else { Utils.Log(String.Format("{0}: {1}", ++_compiledFileCount, sourceUnit.Path), "LOAD_COMPILED"); @@ -486,12 +549,22 @@ private class ResolvedFile { AddCompiledFile(fullPath, compiledCode); - CompileAndRun(globalScope, compiledCode); + return compiledCode; } } - internal object CompileAndRun(Scope globalScope, ScriptCode/*!*/ code) { - return globalScope != null ? code.Run(globalScope) : code.Run(); + internal Scope Execute(Scope globalScope, ScriptCode/*!*/ code) { + if (globalScope == null || code.LanguageContext != _context) { + globalScope = code.CreateScope(); + if (code.SourceUnit.Path != null) { + LoadedScripts[Platform.GetFullPath(code.SourceUnit.Path)] = globalScope; + } + code.Run(globalScope); + return globalScope; + } else { + code.Run(globalScope); + return null; + } } private ResolvedFile FindFile(string/*!*/ path, bool appendExtensions, string[] sourceFileExtensions) { diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyContext.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyContext.cs index be847439e9..c4a5038ca4 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyContext.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyContext.cs @@ -1237,12 +1237,12 @@ public RubyContext(ScriptDomainManager/*!*/ manager, IDictionary // thread-safe: public MethodResolutionResult ResolveMethod(object target, string/*!*/ name, bool includePrivate) { var owner = GetImmediateClassOf(target); - return owner.ResolveMethod(name, includePrivate ? RubyClass.IgnoreVisibility : owner); + return owner.ResolveMethod(name, includePrivate ? VisibilityContext.AllVisible : new VisibilityContext(owner)); } // thread-safe: - public MethodResolutionResult ResolveMethod(object target, string/*!*/ name, RubyClass visibilityContext) { - return GetImmediateClassOf(target).ResolveMethod(name, visibilityContext); + public MethodResolutionResult ResolveMethod(object target, string/*!*/ name, VisibilityContext visibility) { + return GetImmediateClassOf(target).ResolveMethod(name, visibility); } // thread-safe: diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyOps.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyOps.cs index ecf259af3d..c67c24db34 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyOps.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyOps.cs @@ -553,7 +553,7 @@ public static partial class RubyOps { public static void UndefineMethod(RubyScope/*!*/ scope, string/*!*/ name) { RubyModule owner = scope.GetInnerMostModuleForMethodLookup(); - if (!owner.ResolveMethod(name, RubyClass.IgnoreVisibility).Found) { + if (!owner.ResolveMethod(name, VisibilityContext.AllVisible).Found) { throw RubyExceptions.CreateUndefinedMethodError(owner, name); } owner.UndefineMethod(name); @@ -563,7 +563,7 @@ public static partial class RubyOps { public static bool IsDefinedMethod(object self, RubyScope/*!*/ scope, string/*!*/ name) { // MRI: this is different from UndefineMethod, it behaves like Kernel#method (i.e. doesn't use lexical scope): // TODO: visibility - return scope.RubyContext.ResolveMethod(self, name, RubyClass.IgnoreVisibility).Found; + return scope.RubyContext.ResolveMethod(self, name, VisibilityContext.AllVisible).Found; } #endregion diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyScope.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyScope.cs index 1d5ec7e016..59a7ad8a1e 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyScope.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyScope.cs @@ -916,39 +916,58 @@ public sealed class RubyTopLevelScope : RubyClosureScope { // "method_missing" on main singleton in DLR Scope bound code. // Might be called via a site -> needs to be public in partial trust. public static object TopMethodMissing(RubyScope/*!*/ localScope, BlockParam block, object/*!*/ self, SymbolId name, [NotNull]params object[]/*!*/ args) { - Assert.NotNull(localScope, self); - Debug.Assert(!localScope.IsEmpty); - Scope globalScope = localScope.GlobalScope.Scope; - Debug.Assert(globalScope != null); + return ScopeMethodMissing(localScope.RubyContext, localScope.GlobalScope.Scope, block, self, name, args); + } + + public static object ScopeMethodMissing(RubyContext/*!*/ context, Scope/*!*/ globalScope, BlockParam block, object self, SymbolId name, object[]/*!*/ args) { + Assert.NotNull(context, globalScope); + + string str = SymbolTable.IdToString(name); + if (str.LastCharacter() == '=') { + if (args.Length != 1) { + throw RubyOps.MakeWrongNumberOfArgumentsError(args.Length, 1); + } + + // Consider this case: + // There is {"Foo" -> 1} in the scope. + // x.foo += 1 + // Without name mangling this would result to {"Foo" -> 1, "foo" -> 2} while the expected result is {"Foo" -> 2}. + + str = str.Substring(0, str.Length - 1); + name = SymbolTable.StringToId(str); - // TODO: error when arguments non-empty, block != null, ... + if (!globalScope.ContainsName(name)) { + var unmangled = SymbolTable.StringToId(RubyUtils.TryUnmangleName(str)); + if (!unmangled.IsEmpty && globalScope.ContainsName(unmangled)) { + name = unmangled; + } + } + + var value = args[0]; + globalScope.SetName(name, value); + return value; + } else { + if (args.Length != 0) { + throw RubyOps.MakeWrongNumberOfArgumentsError(args.Length, 0); + } - if (args.Length == 0) { object value; if (globalScope.TryGetName(name, out value)) { return value; } - string str = SymbolTable.IdToString(name); string unmangled = RubyUtils.TryUnmangleName(str); if (unmangled != null && globalScope.TryGetName(SymbolTable.StringToId(unmangled), out value)) { return value; } - if (str == "scope") { + if (self != null && str == "scope") { return self; } - } else if (args.Length == 1) { - string str = SymbolTable.IdToString(name); - if (str.LastCharacter() == '=') { - SymbolId plainName = SymbolTable.StringToId(str.Substring(0, str.Length - 1)); - globalScope.SetName(plainName, args[0]); - return args[0]; - } } // TODO: call super - throw RubyExceptions.CreateMethodMissing(localScope.RubyContext, self, SymbolTable.IdToString(name)); + throw RubyExceptions.CreateMethodMissing(context, self, SymbolTable.IdToString(name)); } #endregion diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyUtils.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyUtils.cs index b9ebcbfe32..83c73cca8f 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyUtils.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/RubyUtils.cs @@ -188,67 +188,165 @@ public static class RubyUtils { #region Names - // Unmangles a method name. Not all names can be unmangled. - // For a name to be unmangle-able, it must be lower_case_with_underscores. - // If a name can't be unmangled, this function returns null + /// + /// Converts a Ruby name to PascalCase name (foo_bar -> FooBar). + /// Returns null if the name is not a well-formed Ruby name (it contains upper-case latter or subsequent underscores). + /// Characters that are not upper case letters are treated as lower-case letters. + /// public static string TryUnmangleName(string/*!*/ name) { - if (name.ToUpper().Equals("INITIALIZE")) { - // Special case for compatibility with CLR - return name; + ContractUtils.RequiresNotNull(name, "name"); + if (name.Length == 0) { + return null; } - StringBuilder sb = new StringBuilder(name.Length); - bool upcase = true; - foreach (char c in name) { - if (char.IsUpper(c)) { - // can't unmangle a name with uppercase letters + StringBuilder mangled = new StringBuilder(); + + bool lastWasSpecial = false; + int i = 0, j = 0; + while (i < name.Length) { + char c; + while (j < name.Length && (c = name[j]) != '_') { + if (Char.IsUpper(c)) { + return null; + } + j++; + } + + if (j == i || j == name.Length - 1) { return null; } - if (c == '_') { - if (upcase) { - // can't unmangle a name with consecutive or leading underscores + if (j - i == 1) { + // "ip_f_xxx" -/-> "IPFXxx" + if (lastWasSpecial) { return null; } - upcase = true; + mangled.Append(name[i].ToUpperInvariant()); + lastWasSpecial = false; } else { - if (upcase) { - sb.Append(char.ToUpper(c)); - upcase = false; + string special = MapSpecialWord(name, i, j - i); + if (special != null) { + // "ip_ip" -/-> "IPIP" + if (lastWasSpecial) { + return null; + } + mangled.Append(special.ToUpperInvariant()); + lastWasSpecial = true; } else { - sb.Append(c); + mangled.Append(name[i].ToUpperInvariant()); + mangled.Append(name, i + 1, j - i - 1); + lastWasSpecial = false; } } + + i = ++j; } - if (upcase) { - // string was empty or ended with an underscore, can't unmangle - return null; - } - return sb.ToString(); + + return mangled.ToString(); } - public static string/*!*/ MangleName(string/*!*/ name) { - Assert.NotNull(name); + /// + /// Converts a camelCase or PascalCase name to a Ruby name (FooBar -> foo_bar). + /// Returns null if the name is not in camelCase or PascalCase (FooBAR, foo, etc.). + /// Characters that are not upper case letters are treated as lower-case letters. + /// + public static string TryMangleName(string/*!*/ name) { + ContractUtils.RequiresNotNull(name, "name"); + StringBuilder mangled = null; + int i = 0; + while (i < name.Length) { + char c = name[i]; + if (Char.IsUpper(c)) { + int j = i + 1; + while (j < name.Length && Char.IsUpper(name, j)) { + j++; + } - if (name.ToUpper().Equals("INITIALIZE")) { - // Special case for compatibility with CLR - return name; - } + if (j < name.Length) { + j--; + } + + if (mangled == null) { + mangled = new StringBuilder(); + mangled.Append(name, 0, i); + } - StringBuilder result = new StringBuilder(name.Length); + if (i > 0) { + mangled.Append('_'); + } - for (int i = 0; i < name.Length; i++) { - if (Char.IsUpper(name[i])) { - if (!(i == 0 || i + 1 < name.Length && Char.IsUpper(name[i + 1]) || i + 1 == name.Length && Char.IsUpper(name[i - 1]))) { - result.Append('_'); + int count = j - i; + if (count == 0) { + // NaN{end}, NaNXxx + if (i + 2 < name.Length && + Char.IsUpper(name[i + 2]) && + (i + 3 == name.Length || Char.IsUpper(name[i + 3]) && + (i + 4 < name.Length && !Char.IsUpper(name[i + 4])))) { + return null; + } else { + // X{end}, In, NaN, Xml, Html, ... + mangled.Append(c.ToLowerInvariant()); + i++; + } + } else if (count == 1) { + // FXx + mangled.Append(c.ToLowerInvariant()); + i++; + } else { + // FOXxx, FOOXxx, FOOOXxx, ... + string special = MapSpecialWord(name, i, count); + if (special != null) { + mangled.Append(special.ToLowerInvariant()); + i = j; + } else { + return null; + } } - result.Append(Char.ToLower(name[i])); } else { - result.Append(name[i]); + if (mangled != null) { + mangled.Append(c); + } + i++; } } - return result.ToString(); + return mangled != null ? mangled.ToString() : null; + } + + private static string MapSpecialWord(string/*!*/ name, int start, int count) { + if (count == 2) { + return IsTwoLetterWord(name, start) ? null : name.Substring(start, count); + } + + return null; + } + + private static bool IsTwoLetterWord(string/*!*/ str, int index) { + int c = LetterPair(str, index); + switch (c) { + case ('a' << 8) | 't': + case ('a' << 8) | 's': + case ('b' << 8) | 'y': + case ('d' << 8) | 'o': + case ('i' << 8) | 'd': + case ('i' << 8) | 't': + case ('i' << 8) | 'f': + case ('i' << 8) | 'n': + case ('i' << 8) | 's': + case ('g' << 8) | 'o': + case ('m' << 8) | 'y': + case ('o' << 8) | 'f': + case ('o' << 8) | 'k': + case ('o' << 8) | 'n': + case ('t' << 8) | 'o': + case ('u' << 8) | 'p': + return true; + } + return false; + } + + private static int LetterPair(string/*!*/ str, int index) { + return (str[index + 1] & 0xff00) == 0 ? (str[index].ToLowerInvariant() << 8) | str[index + 1].ToLowerInvariant() : -1; } #endregion diff --git a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Utils.cs b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Utils.cs index 3523b85203..fbec6d7bd9 100644 --- a/Merlin/Main/Languages/Ruby/Ruby/Runtime/Utils.cs +++ b/Merlin/Main/Languages/Ruby/Ruby/Runtime/Utils.cs @@ -21,6 +21,7 @@ using System.Collections; using System.Collections.Generic; using IronRuby.Builtins; +using System.Globalization; namespace IronRuby.Runtime { public static class Utils { @@ -327,6 +328,19 @@ public static class Utils { return defaultResult; } + internal static bool SubstringEquals(string/*!*/ name, int start, int count, string/*!*/ other) { + if (count != other.Length) { + return false; + } + + for (int i = 0; i < count; i++) { + if (name[start + i] != other[i]) { + return false; + } + } + return true; + } + public static TOutput[]/*!*/ ConvertAll(this TInput[]/*!*/ array, Converter/*!*/ converter) { var result = new TOutput[array.Length]; for (int i = 0; i < array.Length; i++) { @@ -375,6 +389,24 @@ public static class Utils { public static char ToUpperHexDigit(this int digit) { return (char)((digit < 10) ? '0' + digit : 'A' + digit - 10); } + + public static char ToUpperInvariant(this char c) { + return Char.ToUpper(c, CultureInfo.InvariantCulture); + } + + public static char ToLowerInvariant(this char c) { + return Char.ToLower(c, CultureInfo.InvariantCulture); + } + +#if SILVERLIGHT + public static string/*!*/ ToUpperInvariant(this string/*!*/ str) { + return str.ToUpper(CultureInfo.InvariantCulture); + } + + public static string/*!*/ ToLowerInvariant(this string/*!*/ str) { + return str.ToLower(CultureInfo.InvariantCulture); + } +#endif } } diff --git a/Merlin/Main/Languages/Ruby/RubyCodeCoverage.testrunconfig b/Merlin/Main/Languages/Ruby/RubyCodeCoverage.testrunconfig deleted file mode 100644 index f100917f79..0000000000 --- a/Merlin/Main/Languages/Ruby/RubyCodeCoverage.testrunconfig +++ /dev/null @@ -1,24 +0,0 @@ - - - This is a default test run configuration for a local test run. - - - - - - - - - - - -
-
-
-
- - - - - - \ No newline at end of file diff --git a/Merlin/Main/Languages/Ruby/RubyCodeCoverage.vsmdi b/Merlin/Main/Languages/Ruby/RubyCodeCoverage.vsmdi deleted file mode 100644 index b19732b1dd..0000000000 --- a/Merlin/Main/Languages/Ruby/RubyCodeCoverage.vsmdi +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/css/screen.css b/Merlin/Main/Languages/Ruby/Samples/Tutorial/css/screen.css index 44cfe54792..6e55d9c2a9 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/css/screen.css +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/css/screen.css @@ -1,15 +1,15 @@ -html, body { - height: 99%; - overflow: auto; -} -body { - padding: 0; - margin: 0; -} -#silverlightControlHost { - height: 100%; -} -#errorLocation { - font-size: small; - color: Gray; -} +html, body { + height: 99%; + overflow: auto; +} +body { + padding: 0; + margin: 0; +} +#silverlightControlHost { + height: 100%; +} +#errorLocation { + font-size: small; + color: Gray; +} diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL.sln b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL.sln index 502acdb837..74da5ca209 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL.sln +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL.sln @@ -1,17 +1,17 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TutorialSL", "TutorialSL\TutorialSL.csproj", "{102A0325-55BF-475B-8536-018F7D913B83}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {102A0325-55BF-475B-8536-018F7D913B83}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {102A0325-55BF-475B-8536-018F7D913B83}.Debug|Any CPU.Build.0 = Debug|Any CPU - {102A0325-55BF-475B-8536-018F7D913B83}.Release|Any CPU.ActiveCfg = Release|Any CPU - {102A0325-55BF-475B-8536-018F7D913B83}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TutorialSL", "TutorialSL\TutorialSL.csproj", "{102A0325-55BF-475B-8536-018F7D913B83}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {102A0325-55BF-475B-8536-018F7D913B83}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {102A0325-55BF-475B-8536-018F7D913B83}.Debug|Any CPU.Build.0 = Debug|Any CPU + {102A0325-55BF-475B-8536-018F7D913B83}.Release|Any CPU.ActiveCfg = Release|Any CPU + {102A0325-55BF-475B-8536-018F7D913B83}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/App.xaml b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/App.xaml index efc16b3b42..88b31ab738 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/App.xaml +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/App.xaml @@ -1,8 +1,8 @@ - - - - - + + + + + diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/App.xaml.cs b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/App.xaml.cs index 020dd1d302..95af3a0ed5 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/App.xaml.cs +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/App.xaml.cs @@ -1,65 +1,65 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Animation; -using System.Windows.Shapes; - -namespace TutorialSL -{ - public partial class App : Application - { - public App() - { - this.Startup += this.Application_Startup; - this.Exit += this.Application_Exit; - this.UnhandledException += this.Application_UnhandledException; - - InitializeComponent(); - } - - private void Application_Startup(object sender, StartupEventArgs e) - { - this.RootVisual = new MainPage(); - } - - private void Application_Exit(object sender, EventArgs e) - { - } - - private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) - { - // If the app is running outside of the debugger then report the exception using - // the browser's exception mechanism. On IE this will display it a yellow alert - // icon in the status bar and Firefox will display a script error. - if (!System.Diagnostics.Debugger.IsAttached) - { - - // NOTE: This will allow the application to continue running after an exception has been thrown - // but not handled. - // For production applications this error handling should be replaced with something that will - // report the error to the website and stop the application. - e.Handled = true; - Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); }); - } - } - - private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e) - { - try - { - string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace; - errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n"); - - System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");"); - } - catch (Exception) - { - } - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Shapes; + +namespace TutorialSL +{ + public partial class App : Application + { + public App() + { + this.Startup += this.Application_Startup; + this.Exit += this.Application_Exit; + this.UnhandledException += this.Application_UnhandledException; + + InitializeComponent(); + } + + private void Application_Startup(object sender, StartupEventArgs e) + { + this.RootVisual = new MainPage(); + } + + private void Application_Exit(object sender, EventArgs e) + { + } + + private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) + { + // If the app is running outside of the debugger then report the exception using + // the browser's exception mechanism. On IE this will display it a yellow alert + // icon in the status bar and Firefox will display a script error. + if (!System.Diagnostics.Debugger.IsAttached) + { + + // NOTE: This will allow the application to continue running after an exception has been thrown + // but not handled. + // For production applications this error handling should be replaced with something that will + // report the error to the website and stop the application. + e.Handled = true; + Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); }); + } + } + + private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e) + { + try + { + string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace; + errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n"); + + System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");"); + } + catch (Exception) + { + } + } + } +} diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/MainPage.xaml.cs b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/MainPage.xaml.cs index b6b1d5fbe6..d4cd235e56 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/MainPage.xaml.cs +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/MainPage.xaml.cs @@ -1,42 +1,42 @@ -/* **************************************************************************** - * - * Copyright (c) Microsoft Corporation. - * - * This source code is subject to terms and conditions of the Microsoft Public License. A - * copy of the license can be found in the License.html file at the root of this distribution. If - * you cannot locate the Microsoft Public License, 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 Microsoft Public License. - * - * You must not remove this notice, or any other, from this software. - * - * - * ***************************************************************************/ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Shapes; - -namespace TutorialSL -{ - /// - /// Interaction logic for MainWindow.xaml - /// - public partial class MainPage : UserControl - { - public MainPage() - { - this.InitializeComponent(); - - // Insert code required on object creation below this point. - } - } -} +/* **************************************************************************** + * + * Copyright (c) Microsoft Corporation. + * + * This source code is subject to terms and conditions of the Microsoft Public License. A + * copy of the license can be found in the License.html file at the root of this distribution. If + * you cannot locate the Microsoft Public License, 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 Microsoft Public License. + * + * You must not remove this notice, or any other, from this software. + * + * + * ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; + +namespace TutorialSL +{ + /// + /// Interaction logic for MainWindow.xaml + /// + public partial class MainPage : UserControl + { + public MainPage() + { + this.InitializeComponent(); + + // Insert code required on object creation below this point. + } + } +} diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/Properties/AppManifest.xml b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/Properties/AppManifest.xml index 761028400f..7bc277be05 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/Properties/AppManifest.xml +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/Properties/AppManifest.xml @@ -1,5 +1,5 @@ - - - + + + \ No newline at end of file diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/Properties/AssemblyInfo.cs b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/Properties/AssemblyInfo.cs index 30d11ad89d..adffac2d9f 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/Properties/AssemblyInfo.cs +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/Properties/AssemblyInfo.cs @@ -1,37 +1,37 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("TutorialSL")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("TutorialSL")] -[assembly: AssemblyCopyright("Copyright © 2009")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("102a0325-55bf-475b-8536-018f7d913b83")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] - -[assembly: AssemblyVersion("1.0.0.0")] +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("TutorialSL")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("TutorialSL")] +[assembly: AssemblyCopyright("Copyright © 2009")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("102a0325-55bf-475b-8536-018f7d913b83")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] + +[assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/StepControl.xaml.cs b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/StepControl.xaml.cs index 8cbec20fa0..631f4d8dff 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/StepControl.xaml.cs +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/StepControl.xaml.cs @@ -1,39 +1,39 @@ -/* **************************************************************************** - * - * Copyright (c) Microsoft Corporation. - * - * This source code is subject to terms and conditions of the Microsoft Public License. A - * copy of the license can be found in the License.html file at the root of this distribution. If - * you cannot locate the Microsoft Public License, 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 Microsoft Public License. - * - * You must not remove this notice, or any other, from this software. - * - * - * ***************************************************************************/ - -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Shapes; - -namespace TutorialSL -{ - /// - /// Interaction logic for StepControl.xaml - /// - public partial class StepControl : UserControl - { - public StepControl() - { - this.InitializeComponent(); - } - } -} +/* **************************************************************************** + * + * Copyright (c) Microsoft Corporation. + * + * This source code is subject to terms and conditions of the Microsoft Public License. A + * copy of the license can be found in the License.html file at the root of this distribution. If + * you cannot locate the Microsoft Public License, 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 Microsoft Public License. + * + * You must not remove this notice, or any other, from this software. + * + * + * ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; + +namespace TutorialSL +{ + /// + /// Interaction logic for StepControl.xaml + /// + public partial class StepControl : UserControl + { + public StepControl() + { + this.InitializeComponent(); + } + } +} diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialControl.xaml b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialControl.xaml index 513d7c812e..4b366b5b6d 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialControl.xaml +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialControl.xaml @@ -17,7 +17,7 @@ - + diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialControl.xaml.cs b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialControl.xaml.cs index 486210115c..62d1329645 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialControl.xaml.cs +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialControl.xaml.cs @@ -1,39 +1,39 @@ -/* **************************************************************************** - * - * Copyright (c) Microsoft Corporation. - * - * This source code is subject to terms and conditions of the Microsoft Public License. A - * copy of the license can be found in the License.html file at the root of this distribution. If - * you cannot locate the Microsoft Public License, 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 Microsoft Public License. - * - * You must not remove this notice, or any other, from this software. - * - * - * ***************************************************************************/ - -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Shapes; - -namespace TutorialSL -{ - /// - /// Interaction logic for TutorialControl.xaml - /// - public partial class TutorialControl : UserControl - { - public TutorialControl() - { - this.InitializeComponent(); - } - } -} +/* **************************************************************************** + * + * Copyright (c) Microsoft Corporation. + * + * This source code is subject to terms and conditions of the Microsoft Public License. A + * copy of the license can be found in the License.html file at the root of this distribution. If + * you cannot locate the Microsoft Public License, 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 Microsoft Public License. + * + * You must not remove this notice, or any other, from this software. + * + * + * ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; + +namespace TutorialSL +{ + /// + /// Interaction logic for TutorialControl.xaml + /// + public partial class TutorialControl : UserControl + { + public TutorialControl() + { + this.InitializeComponent(); + } + } +} diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialPage.xaml b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialPage.xaml index d0393369ac..af4b4777d2 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialPage.xaml +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialPage.xaml @@ -22,7 +22,7 @@ - + Section complete!" diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialPage.xaml.cs b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialPage.xaml.cs index 33658b1e81..8e2d590d87 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialPage.xaml.cs +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialPage.xaml.cs @@ -1,24 +1,24 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Shapes; - -namespace TutorialSL -{ - /// - /// Interaction logic for TutorialPage.xaml - /// - public partial class TutorialPage : UserControl - { - public TutorialPage() - { - this.InitializeComponent(); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; + +namespace TutorialSL +{ + /// + /// Interaction logic for TutorialPage.xaml + /// + public partial class TutorialPage : UserControl + { + public TutorialPage() + { + this.InitializeComponent(); + } + } +} diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialSL.csproj b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialSL.csproj index 83411e9a8b..bf4c725849 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialSL.csproj +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/design/TutorialSL/TutorialSL.csproj @@ -1,107 +1,107 @@ - - - Debug - AnyCPU - 3.0.1921.0 - {102a0325-55bf-475b-8536-018f7d913b83} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Library - Properties - TutorialSL - TutorialSL - TutorialSL - 1.0.0.* - 0 - false - v3.5 - true - true - TutorialSL.xap - true - Properties\AppManifest.xml - TutorialSL.App - true - true - false - true - TestPage.html - - - true - full - false - Bin\Debug - DEBUG;TRACE;SILVERLIGHT - true - true - prompt - 4 - - - pdbonly - true - Bin\Release - TRACE;SILVERLIGHT - true - true - prompt - 4 - - - - - - - - - - - - - - - MSBuild:MarkupCompilePass1 - Designer - - - App.xaml - - - MainPage.xaml - - - MSBuild:MarkupCompilePass1 - Designer - - - MSBuild:MarkupCompilePass1 - Designer - - - MSBuild:MarkupCompilePass1 - Designer - - - MSBuild:MarkupCompilePass1 - Designer - - - PreserveNewest - false - - - - StepControl.xaml - - - TutorialControl.xaml - - - TutorialPage.xaml - - - - - - + + + Debug + AnyCPU + 3.0.1921.0 + {102a0325-55bf-475b-8536-018f7d913b83} + {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + Library + Properties + TutorialSL + TutorialSL + TutorialSL + 1.0.0.* + 0 + false + v3.5 + true + true + TutorialSL.xap + true + Properties\AppManifest.xml + TutorialSL.App + true + true + false + true + TestPage.html + + + true + full + false + Bin\Debug + DEBUG;TRACE;SILVERLIGHT + true + true + prompt + 4 + + + pdbonly + true + Bin\Release + TRACE;SILVERLIGHT + true + true + prompt + 4 + + + + + + + + + + + + + + + MSBuild:MarkupCompilePass1 + Designer + + + App.xaml + + + MainPage.xaml + + + MSBuild:MarkupCompilePass1 + Designer + + + MSBuild:MarkupCompilePass1 + Designer + + + MSBuild:MarkupCompilePass1 + Designer + + + MSBuild:MarkupCompilePass1 + Designer + + + PreserveNewest + false + + + + StepControl.xaml + + + TutorialControl.xaml + + + TutorialPage.xaml + + + + + + \ No newline at end of file diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/gui_tutorial.rb b/Merlin/Main/Languages/Ruby/Samples/Tutorial/gui_tutorial.rb index c3decddc37..bd9f17a47b 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/gui_tutorial.rb +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/gui_tutorial.rb @@ -1,455 +1,455 @@ -$:.unshift File.dirname(__FILE__) + "/Libs" - -require File.dirname(__FILE__) + '/wpf' -include Wpf - -require 'tutorial' - -module GuiTutorial - - class Tutorial - attr_reader :tasks, :task, :chapter, :current_tutorial - - # TODO: Figure out how to remove this condition: - # - # When the "next_chapter" button is focused and the enter-button is pressed, - # somewhere along that process the "repl_input" TextBox gets focus, but - # then the "repl_input.key_up" fires from the previous enter-button press, - # causing two extra lines in the repl history. - # - # This flag shunts the first key_up event, and then is set back to false. - # This ignores all first-keypresses that are "enter", hackily removing the - # issue, since "enter" should never really be the first key pressed. - # Definitely not a perfect solution. - attr_accessor :handling_next_chapter - - def initialize(t, window) - @current_tutorial ||= ::Tutorial.get_tutorial(t) - @window = GuiTutorial::Window.current - end - - def self.all - @tutorials ||= ::Tutorial.all - end - - def reset - @chapter = nil - @tasks = nil - @window.tutorial_body.children.clear - end - - def start - reset - Window.show_tutorial - - unless SILVERLIGHT - @window.chapters.items_source = @current_tutorial.sections - @window.chapters.mouse_left_button_up do |t, e| - select_section_or_chapter t.selected_item - end - end - - @window.next_chapter.click do |t, e| - @handling_next_chapter = true - select_section_or_chapter @chapter.next_item if @chapter - end - - select_chapter(@current_tutorial.first_chapter, @current_tutorial.first_section) - end - - def select_section_or_chapter(item) - return unless item - case item - when ::Tutorial::Section: select_section item - when ::Tutorial::Chapter: select_chapter item - else - raise "Unknown selection type: #{item}" - end - end - - def select_chapter(chapter, section = nil) - if section - @window.set_or_collapse(:pre_exercise, section.introduction) do |obj, value| - obj.document = value - end - else - @window.pre_exercise.collapse! - end - @chapter = chapter - @window.set_or_collapse(:exercise, @chapter.introduction) do |obj, value| - obj.document = value - end - - @window.tutorial_body.children.clear - @tasks = @chapter.tasks.clone - select_next_task - end - - def select_section(section) - reset - @window.set_or_collapse(:exercise, section.introduction) do |obj, value| - obj.document = value - end - @window.pre_exercise.collapse! - end - - def select_next_task - unless @tasks.empty? - @task = @tasks.shift - @window.next_step - if @task.description - fd = FlowDocument.from_simple_markup @task.description - fd << "Full path: #{@task.source_files.tr('/', '\\')}" if @task.source_files - return select_next_task if not @task.should_run? Window.repl.context.bind - @task.setup.call(Window.repl.context.bind) if @task.setup - if @task.code - unless SILVERLIGHT - p = Paragraph.new Run.new(@task.code_string) - p.font_family = FontFamily.new "Consolas" - p.font_weight = FontWeights.Bold - fd.Blocks.Add p - else - fd += "\n\n#{@task.code_string}" - end - end - end - @window.set_or_collapse(:step_title, @task.title) do |obj, value| - obj.text = value - end - - @window.step_description.document = fd - @window.tutorial_scroll.scroll_to_bottom - else - if @chapter.next_item - @window.complete.show! - @window.tutorial_scroll.scroll_to_bottom - if @window.current_step? - @window.repl_input.collapse! - @window.repl_input_arrow.collapse! - end - @window.set_or_collapse(:complete_title, @chapter.summary.title) do |obj, value| - obj.text = value - end if @chapter.summary - @window.set_or_collapse(:complete_body, @chapter.summary.body) do |obj, value| - obj.document = FlowDocument.from_simple_markup value - end if @chapter.summary - @window.next_chapter.focus - else - if @current_tutorial.summary && @current_tutorial.summary.body - @window.exercise.document = FlowDocument.from_simple_markup(@current_tutorial.summary.body) - else - @window.exercise.document = FlowDocument.from_simple_markup("Tutorial complete!") - end - @window.exercise.show! - @window.tutorial_body.children.clear - @window.tutorial_scroll.scroll_to_top - end - end - end - - def process_result(result) - if @task and @task.success?(result) - select_next_task - end - end - end - - class Window - module Accessors - def current_step - @current_step ||= Step.new(Window.tutorial.task, current_step_id, Window.current) - end - - def current_step_id - @current_step_id || 0 - end - - def current_step? - respond_to?(:"step_#{current_step_id}") - end - - def current_step_object - current_step.object - end - - def next_step - complete.collapse! - if current_step? - repl_input.collapse! - repl_input_arrow.collapse! - end - - @current_step = nil - @current_step_id ||= -1 - @current_step_id += 1 - - current_step.show - end - - def reset_step - @current_step_id = 0 - @current_step = nil - end - - def cache_step(name, object) - instance_variable_set(:"@#{name}", object) - self.class.class_eval { attr_reader :"#{name}" } - end - - delegate_methods [:step_title, :step_description], :to => :current_step_object, :append => :current_step_id - - delegate_methods [:repl_input, :repl_input_arrow, :repl_history], - :to => :current_step_object, :prepend => 'step', :append => :current_step_id - end - - class << self - attr_reader :step_xaml, :tut_xaml - attr_reader :repl, :tutorial - - def current - @window ||= create - end - - def create - win = XamlReader.load xaml do |win| - win.main.children.clear - - GuiTutorial::Tutorial.all.each_with_index do |(path,tutorial), index| - tutorial_id, tutorial_title_id, tutorial_desc_id = "tutorial_#{index}", "tutorial_title_#{index}", "tutorial_desc_#{index}" - tutorial_id_OnMouseLeave_BeginStoryboard = "tutorial_#{index}_OnMouseLeave_BeginStoryboard" - - XamlReader.erb_load(@tut_xaml, binding) do |obj| - obj.send(tutorial_title_id).text = tutorial.name - - obj.send(tutorial_desc_id).document = tutorial.introduction - win.main.children.add obj - - obj.mouse_left_button_up do |t, e| - @tutorial = GuiTutorial::Tutorial.new(path, Window.current) - @tutorial.start - end - - obj.show! - end - end - show_main(win) - @repl = Repl.new - end - class << win - include Accessors - end - win - end - - def show_main(win = current) - win.header_name.text = 'Pick a tutorial' - win.main_scroll.show! - win.tutorial_scroll.collapse! - win.tutorial_nav.collapse! - win.complete.collapse! - if @tutorial - win.header_navigation.show! - win.header_navigation.action.text = "Resume tutorial" - win.header_navigation.action.mouse_left_button_up {|t,e| show_tutorial} - else - win.header_navigation.collapse! - end - end - - def show_tutorial - current.main_scroll.collapse! - current.tutorial_scroll.show! - current.tutorial_nav.show! unless SILVERLIGHT - current.complete.collapse! - current.header_name.text = @tutorial.current_tutorial.name - current.header_navigation.show! - current.header_navigation.action.text = "Back" - current.header_navigation.action.mouse_left_button_up {|t,e| show_main} - end - - def xaml - design = File.dirname(__FILE__) + '/design/' + (SILVERLIGHT ? 'TutorialSL' : 'Tutorial') - @step_xaml, @tut_xaml = ['Step', 'Tutorial'].map do |i| - sx = sanitize_xaml(File.open(design + "/#{i}Control.xaml"){|f| f.read}) - sx.sub!(/(.*?)<\/UserControl>/, '\1') if i == 'Step' - sx.gsub!(/("|\{StaticResource )(\S*?)_id(\S*?)("|\})/, '\1<%= \2_id %>\3\4') - sx.strip - end - - sanitize_xaml( - File.open(design + "/Main#{SILVERLIGHT ? 'Page' : 'Window'}.xaml"){|f| f.read}. - gsub( - //, - File.open(design + "/TutorialPage.xaml"){|f| f.read}. - gsub(//, '')). - gsub(//, '') - ) - end - - private - def sanitize_xaml(xaml) - { - /x:Class=".*?"/ => '', - /xmlns:local=".*?"/ => '', - /mc:Ignorable=".*?"/ => '', - /xmlns:mc=".*?"/ => '', - /xmlns:d=".*?"/ => '', - 'Loaded="Window_Loaded"' => '', - ' ' '', - /d:.*?=".*?"/ => '' - }.inject(xaml) do |_xaml,(k,v)| - _xaml.gsub(k, v) - end.gsub(/(\n|\t)/, ' ').squeeze(' ') - end - end - end - - class Step - @@vars = :step_id, - :step_title_id, :step_description_id, - :step_wrapper_id, :step_repl_id, - :step_repl_history_id, :step_repl_input_id, :step_repl_input_arrow_id - - attr_reader *@@vars - - attr_reader :object - - def initialize(task, element_id, window) - @task = task - @element_id = "step_#{element_id}" - @window = window - raise "Element #{@element_id} already exists" if @window.respond_to? @element_id - init_vars - end - - def show - @object = XamlReader.erb_load(Window.step_xaml, binding) do |obj| - @window.tutorial_body.children.add obj - @window.cache_step(@element_id, obj) - obj.show! - end - - Window.repl.prev_newline = nil - @window.repl_history.text = '' - - @window.repl_input.show! - Window.repl.set_prompt - Window.repl.context.reset_input - - # TODO - Should use TextChanged here - @window.repl_input.key_up do |target, event_args| - if event_args.key == Key.enter && !Window.tutorial.handling_next_chapter - Window.tutorial.process_result Window.repl.on_repl_input - elsif event_args.Key == (!SILVERLIGHT ? Key.System : Key.alt) - # This allows hitting Alt-Enter to automatically enter the code - # It is useful during manual testing of a tutorial's content - if @task.code.respond_to? :to_ary - @task.code.to_ary.each do |code| - Window.current.repl_input.text = code - Window.tutorial.process_result Window.repl.on_repl_input - end - else - Window.current.repl_input.text = @task.code - Window.tutorial.process_result Window.repl.on_repl_input - end - end - Window.tutorial.handling_next_chapter = false - end - - @window.repl_input_arrow.show! - @window.repl_input.focus - end - - private - def init_vars - @@vars.each do |v| - instance_variable_set( - :"@#{v}", - "#{v.to_s.split('_id').first}_#{@window.current_step_id}" - ) - end - end - end - - class Repl - attr_accessor :prev_newline - attr_accessor :context - - def self.repl_puts *a - repl_visible = Window.complete.visibility == System::Windows::Visibility.visible rescue false - if Thread.current[:evaluating_tutorial_input] or not repl_visible - # This is a synchronous "puts" being executed when the user has pressed "Enter" to execute - # a command. In this case, we do the default processing. This ensures that the output - # will get captured in Tutorial::InteractionResult.output, along with any "puts" executed - # by any Ruby files that run - ::Kernel.puts *a - else - # This is an async "puts". It does not make sense to capture this into Tutorial::InteractionResult.output. - # We just ensure that it gets printed in the REPL - a.each { |i| WpfTutorial.tutorial.print_to_repl i.to_s, true } - nil - end - end - - def initialize - @context = ::Tutorial::ReplContext.new - @prev_newline = nil - - # Hook-up "puts" so that we can redirect asynchronous "puts" (typically called from event-handlers) - atleast - # the ones that are entered into the REPL - class << @context.scope - def puts *a - Repl.repl_puts *a - end - end - end - - def history - Window.current.repl_history - end - - def input - Window.current.repl_input - end - - def print(s, new_line = true) - history.text += s - history.text += "\n" if new_line - end - - def set_prompt p = ">>>" - @prompt = p - Window.current.repl_input_arrow.content = p - end - - def on_repl_input - puts "in on_repl_input" - print '' if @prev_newline - history.show! - - input = self.input.text - print "#{@prompt} #{input}" - set_prompt - self.input.text = '' - - result = @context.interact input - print result.output, false unless result.output.empty? - if result.partial_input? - set_prompt "..." - elsif result.error - print result.error.to_s - else - print "=> #{result.result.inspect}" - end - - if history.text.size > 1 - # TODO should be able to do str[-1] on a clrstring - @prev_newline = history.text.to_s[-1] == 10 # '\n' - history.text = history.text.to_s[0..-2].to_clr_string - end - result - end - end - -end +$:.unshift File.dirname(__FILE__) + "/Libs" + +require File.dirname(__FILE__) + '/wpf' +include Wpf + +require 'tutorial' + +module GuiTutorial + + class Tutorial + attr_reader :tasks, :task, :chapter, :current_tutorial + + # TODO: Figure out how to remove this condition: + # + # When the "next_chapter" button is focused and the enter-button is pressed, + # somewhere along that process the "repl_input" TextBox gets focus, but + # then the "repl_input.key_up" fires from the previous enter-button press, + # causing two extra lines in the repl history. + # + # This flag shunts the first key_up event, and then is set back to false. + # This ignores all first-keypresses that are "enter", hackily removing the + # issue, since "enter" should never really be the first key pressed. + # Definitely not a perfect solution. + attr_accessor :handling_next_chapter + + def initialize(t, window) + @current_tutorial ||= ::Tutorial.get_tutorial(t) + @window = GuiTutorial::Window.current + end + + def self.all + @tutorials ||= ::Tutorial.all + end + + def reset + @chapter = nil + @tasks = nil + @window.tutorial_body.children.clear + end + + def start + reset + Window.show_tutorial + + unless SILVERLIGHT + @window.chapters.items_source = @current_tutorial.sections + @window.chapters.mouse_left_button_up do |t, e| + select_section_or_chapter t.selected_item + end + end + + @window.next_chapter.click do |t, e| + @handling_next_chapter = true + select_section_or_chapter @chapter.next_item if @chapter + end + + select_chapter(@current_tutorial.first_chapter, @current_tutorial.first_section) + end + + def select_section_or_chapter(item) + return unless item + case item + when ::Tutorial::Section: select_section item + when ::Tutorial::Chapter: select_chapter item + else + raise "Unknown selection type: #{item}" + end + end + + def select_chapter(chapter, section = nil) + if section + @window.set_or_collapse(:pre_exercise, section.introduction) do |obj, value| + obj.document = value + end + else + @window.pre_exercise.collapse! + end + @chapter = chapter + @window.set_or_collapse(:exercise, @chapter.introduction) do |obj, value| + obj.document = value + end + + @window.tutorial_body.children.clear + @tasks = @chapter.tasks.clone + select_next_task + end + + def select_section(section) + reset + @window.set_or_collapse(:exercise, section.introduction) do |obj, value| + obj.document = value + end + @window.pre_exercise.collapse! + end + + def select_next_task + unless @tasks.empty? + @task = @tasks.shift + @window.next_step + if @task.description + fd = FlowDocument.from_simple_markup @task.description + fd << "Full path: #{@task.source_files.tr('/', '\\')}" if @task.source_files + return select_next_task if not @task.should_run? Window.repl.context.bind + @task.setup.call(Window.repl.context.bind) if @task.setup + if @task.code + unless SILVERLIGHT + p = Paragraph.new Run.new(@task.code_string) + p.font_family = FontFamily.new "Consolas" + p.font_weight = FontWeights.Bold + fd.Blocks.Add p + else + fd += "\n\n#{@task.code_string}" + end + end + end + @window.set_or_collapse(:step_title, @task.title) do |obj, value| + obj.text = value + end + + @window.step_description.document = fd + @window.tutorial_scroll.scroll_to_bottom + else + if @chapter.next_item + @window.complete.show! + @window.tutorial_scroll.scroll_to_bottom + if @window.current_step? + @window.repl_input.collapse! + @window.repl_input_arrow.collapse! + end + @window.set_or_collapse(:complete_title, @chapter.summary.title) do |obj, value| + obj.text = value + end if @chapter.summary + @window.set_or_collapse(:complete_body, @chapter.summary.body) do |obj, value| + obj.document = FlowDocument.from_simple_markup value + end if @chapter.summary + @window.next_chapter.focus + else + if @current_tutorial.summary && @current_tutorial.summary.body + @window.exercise.document = FlowDocument.from_simple_markup(@current_tutorial.summary.body) + else + @window.exercise.document = FlowDocument.from_simple_markup("Tutorial complete!") + end + @window.exercise.show! + @window.tutorial_body.children.clear + @window.tutorial_scroll.scroll_to_top + end + end + end + + def process_result(result) + if @task and @task.success?(result) + select_next_task + end + end + end + + class Window + module Accessors + def current_step + @current_step ||= Step.new(Window.tutorial.task, current_step_id, Window.current) + end + + def current_step_id + @current_step_id || 0 + end + + def current_step? + respond_to?(:"step_#{current_step_id}") + end + + def current_step_object + current_step.object + end + + def next_step + complete.collapse! + if current_step? + repl_input.collapse! + repl_input_arrow.collapse! + end + + @current_step = nil + @current_step_id ||= -1 + @current_step_id += 1 + + current_step.show + end + + def reset_step + @current_step_id = 0 + @current_step = nil + end + + def cache_step(name, object) + instance_variable_set(:"@#{name}", object) + self.class.class_eval { attr_reader :"#{name}" } + end + + delegate_methods [:step_title, :step_description], :to => :current_step_object, :append => :current_step_id + + delegate_methods [:repl_input, :repl_input_arrow, :repl_history], + :to => :current_step_object, :prepend => 'step', :append => :current_step_id + end + + class << self + attr_reader :step_xaml, :tut_xaml + attr_reader :repl, :tutorial + + def current + @window ||= create + end + + def create + win = XamlReader.load xaml do |win| + win.main.children.clear + + GuiTutorial::Tutorial.all.each_with_index do |(path,tutorial), index| + tutorial_id, tutorial_title_id, tutorial_desc_id = "tutorial_#{index}", "tutorial_title_#{index}", "tutorial_desc_#{index}" + tutorial_id_OnMouseLeave_BeginStoryboard = "tutorial_#{index}_OnMouseLeave_BeginStoryboard" + + XamlReader.erb_load(@tut_xaml, binding) do |obj| + obj.send(tutorial_title_id).text = tutorial.name + + obj.send(tutorial_desc_id).document = tutorial.introduction + win.main.children.add obj + + obj.mouse_left_button_up do |t, e| + @tutorial = GuiTutorial::Tutorial.new(path, Window.current) + @tutorial.start + end + + obj.show! + end + end + show_main(win) + @repl = Repl.new + end + class << win + include Accessors + end + win + end + + def show_main(win = current) + win.header_name.text = 'Pick a tutorial' + win.main_scroll.show! + win.tutorial_scroll.collapse! + win.tutorial_nav.collapse! + win.complete.collapse! + if @tutorial + win.header_navigation.show! + win.header_navigation.action.text = "Resume tutorial" + win.header_navigation.action.mouse_left_button_up {|t,e| show_tutorial} + else + win.header_navigation.collapse! + end + end + + def show_tutorial + current.main_scroll.collapse! + current.tutorial_scroll.show! + current.tutorial_nav.show! unless SILVERLIGHT + current.complete.collapse! + current.header_name.text = @tutorial.current_tutorial.name + current.header_navigation.show! + current.header_navigation.action.text = "Back" + current.header_navigation.action.mouse_left_button_up {|t,e| show_main} + end + + def xaml + design = File.dirname(__FILE__) + '/design/' + (SILVERLIGHT ? 'TutorialSL' : 'Tutorial') + @step_xaml, @tut_xaml = ['Step', 'Tutorial'].map do |i| + sx = sanitize_xaml(File.open(design + "/#{i}Control.xaml"){|f| f.read}) + sx.sub!(/(.*?)<\/UserControl>/, '\1') if i == 'Step' + sx.gsub!(/("|\{StaticResource )(\S*?)_id(\S*?)("|\})/, '\1<%= \2_id %>\3\4') + sx.strip + end + + sanitize_xaml( + File.open(design + "/Main#{SILVERLIGHT ? 'Page' : 'Window'}.xaml"){|f| f.read}. + gsub( + //, + File.open(design + "/TutorialPage.xaml"){|f| f.read}. + gsub(//, '')). + gsub(//, '') + ) + end + + private + def sanitize_xaml(xaml) + { + /x:Class=".*?"/ => '', + /xmlns:local=".*?"/ => '', + /mc:Ignorable=".*?"/ => '', + /xmlns:mc=".*?"/ => '', + /xmlns:d=".*?"/ => '', + 'Loaded="Window_Loaded"' => '', + ' ' '', + /d:.*?=".*?"/ => '' + }.inject(xaml) do |_xaml,(k,v)| + _xaml.gsub(k, v) + end.gsub(/(\n|\t)/, ' ').squeeze(' ') + end + end + end + + class Step + @@vars = :step_id, + :step_title_id, :step_description_id, + :step_wrapper_id, :step_repl_id, + :step_repl_history_id, :step_repl_input_id, :step_repl_input_arrow_id + + attr_reader *@@vars + + attr_reader :object + + def initialize(task, element_id, window) + @task = task + @element_id = "step_#{element_id}" + @window = window + raise "Element #{@element_id} already exists" if @window.respond_to? @element_id + init_vars + end + + def show + @object = XamlReader.erb_load(Window.step_xaml, binding) do |obj| + @window.tutorial_body.children.add obj + @window.cache_step(@element_id, obj) + obj.show! + end + + Window.repl.prev_newline = nil + @window.repl_history.text = '' + + @window.repl_input.show! + Window.repl.set_prompt + Window.repl.context.reset_input + + # TODO - Should use TextChanged here + @window.repl_input.key_up do |target, event_args| + if event_args.key == Key.enter && !Window.tutorial.handling_next_chapter + Window.tutorial.process_result Window.repl.on_repl_input + elsif event_args.Key == (!SILVERLIGHT ? Key.System : Key.alt) + # This allows hitting Alt-Enter to automatically enter the code + # It is useful during manual testing of a tutorial's content + if @task.code.respond_to? :to_ary + @task.code.to_ary.each do |code| + Window.current.repl_input.text = code + Window.tutorial.process_result Window.repl.on_repl_input + end + else + Window.current.repl_input.text = @task.code + Window.tutorial.process_result Window.repl.on_repl_input + end + end + Window.tutorial.handling_next_chapter = false + end + + @window.repl_input_arrow.show! + @window.repl_input.focus + end + + private + def init_vars + @@vars.each do |v| + instance_variable_set( + :"@#{v}", + "#{v.to_s.split('_id').first}_#{@window.current_step_id}" + ) + end + end + end + + class Repl + attr_accessor :prev_newline + attr_accessor :context + + def self.repl_puts *a + repl_visible = Window.complete.visibility == System::Windows::Visibility.visible rescue false + if Thread.current[:evaluating_tutorial_input] or not repl_visible + # This is a synchronous "puts" being executed when the user has pressed "Enter" to execute + # a command. In this case, we do the default processing. This ensures that the output + # will get captured in Tutorial::InteractionResult.output, along with any "puts" executed + # by any Ruby files that run + ::Kernel.puts *a + else + # This is an async "puts". It does not make sense to capture this into Tutorial::InteractionResult.output. + # We just ensure that it gets printed in the REPL + a.each { |i| WpfTutorial.tutorial.print_to_repl i.to_s, true } + nil + end + end + + def initialize + @context = ::Tutorial::ReplContext.new + @prev_newline = nil + + # Hook-up "puts" so that we can redirect asynchronous "puts" (typically called from event-handlers) - atleast + # the ones that are entered into the REPL + class << @context.scope + def puts *a + Repl.repl_puts *a + end + end + end + + def history + Window.current.repl_history + end + + def input + Window.current.repl_input + end + + def print(s, new_line = true) + history.text += s + history.text += "\n" if new_line + end + + def set_prompt p = ">>>" + @prompt = p + Window.current.repl_input_arrow.content = p + end + + def on_repl_input + puts "in on_repl_input" + print '' if @prev_newline + history.show! + + input = self.input.text + print "#{@prompt} #{input}" + set_prompt + self.input.text = '' + + result = @context.interact input + print result.output, false unless result.output.empty? + if result.partial_input? + set_prompt "..." + elsif result.error + print result.error.to_s + else + print "=> #{result.result.inspect}" + end + + if history.text.size > 1 + # TODO should be able to do str[-1] on a clrstring + @prev_newline = history.text.to_s[-1] == 10 # '\n' + history.text = history.text.to_s[0..-2].to_clr_string + end + result + end + end + +end diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/index.html b/Merlin/Main/Languages/Ruby/Samples/Tutorial/index.html index cf4456a0fc..acc1e2c3d4 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/index.html +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/index.html @@ -1,114 +1,114 @@ - - - - Silverlight Template - - - - - - - - - - -
- -
- - - - - - - - - - - - - - - - - - - - - - Get Microsoft Silverlight - - - - - - - -
- - - + + + + Silverlight Template + + + + + + + + + + +
+ +
+ + + + + + + + + + + + + + + + + + + + + + Get Microsoft Silverlight + + + + + + + +
+ + + diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/js/error.js b/Merlin/Main/Languages/Ruby/Samples/Tutorial/js/error.js index fbe7954d17..4e16321d37 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/js/error.js +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/js/error.js @@ -1,32 +1,32 @@ -function onSilverlightError(sender, args) { - var appSource = ""; - if (sender != null && sender != 0) { - appSource = sender.getHost().Source; - } - var errorType = args.ErrorType; - var iErrorCode = args.ErrorCode; - - var errMsg = "Unhandled Error in Silverlight 2 Application " + appSource + "\n" ; - - errMsg += "Code: "+ iErrorCode + " \n"; - errMsg += "Category: " + errorType + " \n"; - errMsg += "Message: " + args.ErrorMessage + " \n"; - - if (errorType == "ParserError") - { - errMsg += "File: " + args.xamlFile + " \n"; - errMsg += "Line: " + args.lineNumber + " \n"; - errMsg += "Position: " + args.charPosition + " \n"; - } - else if (errorType == "RuntimeError") - { - if (args.lineNumber != 0) - { - errMsg += "Line: " + args.lineNumber + " \n"; - errMsg += "Position: " + args.charPosition + " \n"; - } - errMsg += "MethodName: " + args.methodName + " \n"; - } - - throw new Error(errMsg); -} +function onSilverlightError(sender, args) { + var appSource = ""; + if (sender != null && sender != 0) { + appSource = sender.getHost().Source; + } + var errorType = args.ErrorType; + var iErrorCode = args.ErrorCode; + + var errMsg = "Unhandled Error in Silverlight 2 Application " + appSource + "\n" ; + + errMsg += "Code: "+ iErrorCode + " \n"; + errMsg += "Category: " + errorType + " \n"; + errMsg += "Message: " + args.ErrorMessage + " \n"; + + if (errorType == "ParserError") + { + errMsg += "File: " + args.xamlFile + " \n"; + errMsg += "Line: " + args.lineNumber + " \n"; + errMsg += "Position: " + args.charPosition + " \n"; + } + else if (errorType == "RuntimeError") + { + if (args.lineNumber != 0) + { + errMsg += "Line: " + args.lineNumber + " \n"; + errMsg += "Position: " + args.charPosition + " \n"; + } + errMsg += "MethodName: " + args.methodName + " \n"; + } + + throw new Error(errMsg); +} diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/sl_tutorial.rb b/Merlin/Main/Languages/Ruby/Samples/Tutorial/sl_tutorial.rb index 4662f94a05..0778f1eba8 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/sl_tutorial.rb +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/sl_tutorial.rb @@ -1,22 +1,22 @@ -# **************************************************************************** -# -# Copyright (c) Microsoft Corporation. -# -# This source code is subject to terms and conditions of the Microsoft Public License. A -# copy of the license can be found in the License.html file at the root of this distribution. If -# you cannot locate the Microsoft Public License, 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 Microsoft Public License. -# -# You must not remove this notice, or any other, from this software. -# -# -# **************************************************************************** - -include Microsoft::Scripting::Silverlight -$stdout = Repl.current.output_buffer -$stderr = Repl.current.output_buffer - -require 'gui_tutorial' - -Application.Current.RootVisual = GuiTutorial::Window.current +# **************************************************************************** +# +# Copyright (c) Microsoft Corporation. +# +# This source code is subject to terms and conditions of the Microsoft Public License. A +# copy of the license can be found in the License.html file at the root of this distribution. If +# you cannot locate the Microsoft Public License, 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 Microsoft Public License. +# +# You must not remove this notice, or any other, from this software. +# +# +# **************************************************************************** + +include Microsoft::Scripting::Silverlight +$stdout = Repl.current.output_buffer +$stderr = Repl.current.output_buffer + +require 'gui_tutorial' + +Application.Current.RootVisual = GuiTutorial::Window.current diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/tutorial-sl.bat b/Merlin/Main/Languages/Ruby/Samples/Tutorial/tutorial-sl.bat index 1af158a0ec..562f720b7a 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/tutorial-sl.bat +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/tutorial-sl.bat @@ -1 +1 @@ -"%~dp0..\..\..\..\Bin\Silverlight Release\Chiron.exe" /b:Tutorial/index.html /d:"%~dp0.." +"%~dp0..\..\..\..\Bin\Silverlight Release\Chiron.exe" /b:Tutorial/index.html /d:"%~dp0.." diff --git a/Merlin/Main/Languages/Ruby/Samples/Tutorial/tutorial.bat b/Merlin/Main/Languages/Ruby/Samples/Tutorial/tutorial.bat index 7af4b38279..04393ce23b 100644 --- a/Merlin/Main/Languages/Ruby/Samples/Tutorial/tutorial.bat +++ b/Merlin/Main/Languages/Ruby/Samples/Tutorial/tutorial.bat @@ -1 +1 @@ -"%~dp0..\..\..\..\Bin\Release\ir.exe" %~dp0wpf_tutorial.rb %* +"%~dp0..\..\..\..\Bin\Release\ir.exe" %~dp0wpf_tutorial.rb %* diff --git a/Merlin/Main/Languages/Ruby/Scripts/ircoverage.bat b/Merlin/Main/Languages/Ruby/Scripts/ircoverage.bat new file mode 100644 index 0000000000..da6dbd7b52 --- /dev/null +++ b/Merlin/Main/Languages/Ruby/Scripts/ircoverage.bat @@ -0,0 +1,22 @@ +set SRC=%MERLIN_ROOT%\Bin\Debug +set DST=%MERLIN_ROOT%\Bin\CodeCoverage +set PERF_TOOLS=%VSINSTALLDIR%\Team Tools\Performance Tools +set VSINSTR="%PERF_TOOLS%\vsinstr.exe" /coverage /outputpath:"%DST%" + +rmdir /s /y "%DST%" +mkdir "%DST%" +xcopy /s /y "%SRC%\*.*" "%DST%" + +%VSINSTR% "%SRC%\ir.exe" +%VSINSTR% "%SRC%\IronRuby.dll" +%VSINSTR% "%SRC%\IronRuby.Yaml.dll" +%VSINSTR% "%SRC%\IronRuby.Libraries.dll" + +"%PERF_TOOLS%\vsperfcmd.exe" /start:coverage /OUTPUT:"%DST%\IronRuby" + +"%DST%\IronRuby.Tests.exe" %* + +"%PERF_TOOLS%\vsperfcmd.exe" /shutdown + +@echo Code Coverage results generated to +@echo %DST%\IronRuby.coverage \ No newline at end of file diff --git a/Merlin/Main/Languages/Ruby/Tests/Interop/net/bcl/string/construction_spec.rb b/Merlin/Main/Languages/Ruby/Tests/Interop/net/bcl/string/construction_spec.rb index 834e43ff05..d3e2bc5901 100644 --- a/Merlin/Main/Languages/Ruby/Tests/Interop/net/bcl/string/construction_spec.rb +++ b/Merlin/Main/Languages/Ruby/Tests/Interop/net/bcl/string/construction_spec.rb @@ -15,14 +15,14 @@ before(:each) do @a = Klass.new.a - @aa = Klass.new.aa + @aa = Klass.new.Aa end it "returns a new System::String from the argument" do System::String.new("a").should == Klass.new.a System::String.new(System::Char.new("a")).should == Klass.new.a - System::String.new(System::Char.new("a"), 2).should == Klass.new.aa - System::String.new(System::Array.of(System::Char).new(2, System::Char.new("a"))).should == Klass.new.aa + System::String.new(System::Char.new("a"), 2).should == Klass.new.Aa + System::String.new(System::Array.of(System::Char).new(2, System::Char.new("a"))).should == Klass.new.Aa end end diff --git a/Merlin/Main/Languages/Ruby/Tests/Interop/net/fields/access_spec.rb b/Merlin/Main/Languages/Ruby/Tests/Interop/net/fields/access_spec.rb index 84007759bf..cbd06436a5 100644 --- a/Merlin/Main/Languages/Ruby/Tests/Interop/net/fields/access_spec.rb +++ b/Merlin/Main/Languages/Ruby/Tests/Interop/net/fields/access_spec.rb @@ -68,7 +68,7 @@ it_behaves_like :accessing_fields, nil end - if IronRuby.dlr_config.private_binding + if IronRuby.configuration.private_binding describe "works with private" do before(:each) do @result = { @@ -137,7 +137,7 @@ end end - if IronRuby.dlr_config.private_binding + if IronRuby.configuration.private_binding describe "with private" do it "fields works" do @klass.privateField = "bar" diff --git a/Merlin/Main/Languages/Ruby/Tests/Interop/net/method/invocation/generic_spec.rb b/Merlin/Main/Languages/Ruby/Tests/Interop/net/method/invocation/generic_spec.rb index 6f1aa15cc0..03f08d3ef6 100644 --- a/Merlin/Main/Languages/Ruby/Tests/Interop/net/method/invocation/generic_spec.rb +++ b/Merlin/Main/Languages/Ruby/Tests/Interop/net/method/invocation/generic_spec.rb @@ -155,7 +155,7 @@ @klass.method(:type_constraint_method).of(SubKlass, Klass).call(SubKlass.new).foo.should == 10 end - if IronRuby.dlr_config.private_binding + if IronRuby.configuration.private_binding it "are callable via call and [] when private" do @private_method_list.each do |m| generic_count, arity = m.match(/_(\d)_generic_(\d)_/)[1..2].map {|e| e.to_i} diff --git a/Merlin/Main/Languages/Ruby/update-git.log b/Merlin/Main/Languages/Ruby/update-git.log index 12a1ac45dcd5e01ab1487365f12cc1bb9c8ced75..166be2717c0c33c841eef4ff391467e5fe061b1d 100644 GIT binary patch delta 3067 zcma)7YiyI(89pa=F1}#w*olL4!3i{&-~>B2J17eVLb#NGb19c#XdK76K;k4$fRZwn zR1>0cCrA-(&6u_xDf)CdC>DvjvwqW5Z7NsZ1 z4zhKui}kP;`tD+@=oO<7-YHq4+rlEOnsu^%wih2Yl`LwYJ^Sfxp*`Urw##i`1GH;^ zEJHuI%M5+iA!1_0bZs6+^m%eTVXvpLHCI^NYj^s+JgWy=pdKcT1Rd0k}PD@h49NU#l#rYD!5iB1T;-g1$XlFzwIB8(uH= z@7XB7zxKYaM0aot?!0I-ZzA&+sdJQ~P)&es=vz6AFI6@Hgx^&i$5$&I7}=pmqt5}u z&QyHrv*40xH+n0ycxzQ24=7ho@h6nOp5(^4LvkLN$M)4Z4^AfrSglABk2!W`wTr{| zqJ=z7#hEo0a-jofFOv#Q7992KQNMOPd9%!nFs|f3q1d12>3B1LF&P*Wx3J#XWYaWI zO83wxjJmaZG1jQX*!pxts-+gXT3TzR7*TnkuXY&fZTV>4mX1TUt?+GkV6!hNQ67R| zMy~2f+O=wFE;&pAYf8e!CKt3Z2ZnZD6iKDoLUQdPnL=1Nuv|)XKMfD9Y|;rPA|kyM z6K-0N*-0b8ZNH3EkhRl)ku2*01RI}rH_}+-PCpB<4O9f8fTGfu0FA;l4$$rpaSzCS zQM{Iwt0F|)I*^7uRSl-A9Ls+SO51GGkrMs*LY1ir5^6}C4wKpn=g*qf{uGpM$*Dss z8X&|7c}9(CuCeq`#u4^B;iX_Nln5bLwGN|wK4|CLPCo6x`0ftM=1NR<)?lOEhWh3_ zSuI`1w0OVWi+wIM=-Mk)_rD&Q=hJVYgxPB}HLp9W6I<>HO zP&=qe!TOF2jAm>k#w!v&*5i%D3^)%A;O@XyY7t`1i>YTE z7|TjY7E(~U;=F0w+`NGc6szo!qaiJRIamqpkiqnL_oJl5=#U!r=MA{<8w;jh$e6!@ zN+?YIvPFta0kxXt*|(ovOkGB;3sRWHJ<-JuV%4(?v3aS*+911Zh;_&Wi%@6=$-0%+ z*T8rz9YaSc(PfB~$XTwXS~QBw4T*LXgSEt*0$``A%8V_xQBc9N2U&f4fCaj%F( zcG9ey-UB3bl-5L&v@64f+^Vt9nHQpGq?0beBD~7CYIev1rwmtuzv4@h=Y}GYM0usv z6U$yg5``iIPruRc>rv)vViA3~jPQvsjiS+nbC;iyUFGBIA{_H;sk2a0HKt%{-JSc5 z0*A64;>1T9MvrU~q8ARnSuL?dgYj*rJ1ijXA-z&H%9A+V84)WcqvER5s;C>`i__-0 z+a-OTsA+LS2)Vj&z9kLyk#xD6fR)3SdCvWTbq&cO?)wH(uAQ_KclJK=czIg3c`MEJ z)7wI?P<(*m%M%yGPQ84NBmZ4v?Do|&3A{Mg_x2w-+HPKm`Tw#pA!fU-Pr&3gH6}j% zG?wy?o^ucS-p+*U#wK2YpWk>FD?VEM`1aVuheN8zrzMK_lf|5u&!IT5`evTW&3*)n zjEuN?XLDLHE0+1;W-I7R{FX2`zMWZyO`k<^^q34^WRq~$C?^u7v2SL= zdLfeXo|D^61qkBxx^VBUM7GS&SIXQ{~%Q&qWnF| zb7Qt|)=P}*hFP{A$(G0wRtYioO17D^13Oix$QDsQqBcwDDOHvi^33F7vhb2i#J)kf zzJb>~#F>1Q;qg#-GEepMdSxuaE8{md@;z!&DqnGK;RWJ{I^(rdO2E(UBzKWi%*)D^ zmq@7i89%?5z&-I_1i2}JSHw?*_);~mP_DJ}MauY7Tpho+gS&WqqMds=&C~iKRZ delta 11 ScmeA;%r)s9Tf-Jcq3r-4KLpwU diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/ActionBinder.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/ActionBinder.cs index 369158238b..a3a7e5002f 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/ActionBinder.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/ActionBinder.cs @@ -88,7 +88,7 @@ public abstract class ActionBinder { /// /// Converts the provided expression to the given type. The expression is safe to evaluate multiple times. /// - public virtual Expression ConvertExpression(Expression expr, Type toType, ConversionResultKind kind, Expression context) { + public virtual Expression ConvertExpression(Expression expr, Type toType, ConversionResultKind kind, OverloadResolverFactory resolverFactory) { ContractUtils.RequiresNotNull(expr, "expr"); ContractUtils.RequiresNotNull(toType, "toType"); @@ -107,12 +107,6 @@ public abstract class ActionBinder { } Type visType = CompilerHelpers.GetVisibleType(toType); - Expression[] args; - if (context != null) { - args = new Expression[] { context, expr }; - } else { - args = new Expression[] { expr }; - } return Expression.Convert(expr, toType); } @@ -193,8 +187,8 @@ public abstract class ActionBinder { ); } - public ErrorInfo MakeStaticPropertyInstanceAccessError(PropertyTracker tracker, bool isAssignment, params Expression[] parameters) { - return MakeStaticPropertyInstanceAccessError(tracker, isAssignment, (IList)parameters); + public ErrorInfo MakeStaticPropertyInstanceAccessError(PropertyTracker tracker, bool isAssignment, params DynamicMetaObject[] parameters) { + return MakeStaticPropertyInstanceAccessError(tracker, isAssignment, (IList)parameters); } /// @@ -202,7 +196,7 @@ public abstract class ActionBinder { /// /// The default behavior is to allow the assignment. /// - public virtual ErrorInfo MakeStaticAssignFromDerivedTypeError(Type accessingType, DynamicMetaObject self, MemberTracker assigning, Expression assignedValue, Expression context) { + public virtual ErrorInfo MakeStaticAssignFromDerivedTypeError(Type accessingType, DynamicMetaObject self, MemberTracker assigning, DynamicMetaObject assignedValue, OverloadResolverFactory context) { switch (assigning.MemberType) { case TrackerTypes.Property: PropertyTracker pt = (PropertyTracker)assigning; @@ -211,7 +205,7 @@ public abstract class ActionBinder { AstUtils.SimpleCallHelper( setter, ConvertExpression( - assignedValue, + assignedValue.Expression, setter.GetParameters()[0].ParameterType, ConversionResultKind.ExplicitCast, context @@ -223,7 +217,7 @@ public abstract class ActionBinder { return ErrorInfo.FromValueNoError( Expression.Assign( Expression.Field(null, ft.Field), - ConvertExpression(assignedValue, ft.FieldType, ConversionResultKind.ExplicitCast, context) + ConvertExpression(assignedValue.Expression, ft.FieldType, ConversionResultKind.ExplicitCast, context) ) ); default: @@ -241,7 +235,7 @@ public abstract class ActionBinder { /// The parameters being used to access the property. This includes the instance as the first entry, any index parameters, and the /// value being assigned as the last entry if isAssignment is true. /// - public virtual ErrorInfo MakeStaticPropertyInstanceAccessError(PropertyTracker tracker, bool isAssignment, IList parameters) { + public virtual ErrorInfo MakeStaticPropertyInstanceAccessError(PropertyTracker tracker, bool isAssignment, IList parameters) { ContractUtils.RequiresNotNull(tracker, "tracker"); ContractUtils.Requires(tracker.IsStatic, "tracker", Strings.ExpectedStaticProperty); ContractUtils.RequiresNotNull(parameters, "parameters"); @@ -296,46 +290,7 @@ public abstract class ActionBinder { } #endregion - - #region Deprecated Error production - - - /// - /// Provides a way for the binder to provide a custom error message when lookup fails. Just - /// doing this for the time being until we get a more robust error return mechanism. - /// - public virtual Expression MakeReadOnlyMemberError(RuleBuilder rule, Type type, string name) { - return rule.MakeError( - Expression.New( - typeof(MissingMemberException).GetConstructor(new Type[] { typeof(string) }), - AstUtils.Constant(name) - ) - ); - } - - /// - /// Provides a way for the binder to provide a custom error message when lookup fails. Just - /// doing this for the time being until we get a more robust error return mechanism. - /// - public virtual Expression MakeUndeletableMemberError(RuleBuilder rule, Type type, string name) { - return MakeReadOnlyMemberError(rule, type, name); - } - - #endregion - - public virtual ErrorInfo MakeEventValidation(RuleBuilder rule, MemberGroup members) { - EventTracker ev = (EventTracker)members[0]; - - // handles in place addition of events - this validates the user did the right thing. - return ErrorInfo.FromValueNoError( - Expression.Call( - typeof(ScriptingRuntimeHelpers).GetMethod("SetEvent"), - AstUtils.Constant(ev), - rule.Parameters[1] - ) - ); - } - + public virtual string GetTypeName(Type t) { return t.Name; } @@ -429,65 +384,44 @@ public abstract class ActionBinder { /// The member which is being returned to the user. /// Tthe type which the memberTrack was accessed from /// - public virtual Expression ReturnMemberTracker(Type type, MemberTracker memberTracker) { + public virtual DynamicMetaObject ReturnMemberTracker(Type type, MemberTracker memberTracker) { if (memberTracker.MemberType == TrackerTypes.Bound) { BoundMemberTracker bmt = (BoundMemberTracker)memberTracker; - return Expression.New( - typeof(BoundMemberTracker).GetConstructor(new Type[] { typeof(MemberTracker), typeof(object) }), - AstUtils.Constant(bmt.BoundTo), - bmt.Instance); + return new DynamicMetaObject( + Expression.New( + typeof(BoundMemberTracker).GetConstructor(new Type[] { typeof(MemberTracker), typeof(object) }), + AstUtils.Constant(bmt.BoundTo), + bmt.Instance.Expression + ), + BindingRestrictions.Empty + ); } - return AstUtils.Constant(memberTracker); + return new DynamicMetaObject(AstUtils.Constant(memberTracker), BindingRestrictions.Empty, memberTracker); } - /// - /// Builds an expression for a call to the provided method using the given expressions. If the - /// method is not static the first parameter is used for the instance. - /// - /// Parameters are converted using the binder's conversion rules. - /// - /// If an incorrect number of parameters is provided MakeCallExpression returns null. - /// - public Expression MakeCallExpression(Expression context, MethodInfo method, IList parameters) { - ParameterInfo[] infos = method.GetParameters(); - Expression callInst = null; - int parameter = 0, startArg = 0; - Expression[] callArgs = new Expression[infos.Length]; - - if (!method.IsStatic) { - callInst = AstUtils.Convert(parameters[0], method.DeclaringType); - parameter = 1; - } - if (infos.Length > 0 && typeof(CodeContext).IsAssignableFrom(infos[0].ParameterType)) { - startArg = 1; - callArgs[0] = context; + public DynamicMetaObject MakeCallExpression(OverloadResolverFactory resolverFactory, MethodInfo method, params DynamicMetaObject[] parameters) { + OverloadResolver resolver; + if (method.IsStatic) { + resolver = resolverFactory.CreateOverloadResolver(parameters, new CallSignature(parameters.Length), CallTypes.None); + } else { + resolver = resolverFactory.CreateOverloadResolver(parameters, new CallSignature(parameters.Length - 1), CallTypes.ImplicitInstance); } + BindingTarget target = resolver.ResolveOverload(method.Name, new MethodBase[] { method }, NarrowingLevel.None, NarrowingLevel.Three); - for (int arg = startArg; arg < infos.Length; arg++) { - if (parameter < parameters.Count) { - callArgs[arg] = ConvertExpression( - parameters[parameter++], - infos[arg].ParameterType, - ConversionResultKind.ExplicitCast, - context - ); - } else { - return null; + if (!target.Success) { + BindingRestrictions restrictions = BindingRestrictions.Combine(parameters); + foreach (DynamicMetaObject mo in parameters) { + restrictions = restrictions.Merge(BindingRestrictions.GetTypeRestriction(mo.Expression, mo.GetLimitType())); } + return DefaultBinder.MakeError( + resolver.MakeInvalidParametersError(target), + restrictions, + typeof(object) + ); } - // check that we used all parameters - if (parameter != parameters.Count) { - return null; - } - - return AstUtils.SimpleCallHelper(callInst, method, callArgs); - } - - - public Expression MakeCallExpression(Expression context, MethodInfo method, params Expression[] parameters) { - return MakeCallExpression(context, method, (IList)parameters); + return new DynamicMetaObject(target.MakeExpression(), target.RestrictedArguments.GetAllRestrictions()); } } } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/BoundMemberTracker.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/BoundMemberTracker.cs index 85c5063712..d545a3866b 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/BoundMemberTracker.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/BoundMemberTracker.cs @@ -14,15 +14,16 @@ * ***************************************************************************/ using System; -using System.Linq.Expressions; +using System.Dynamic; +using Microsoft.Scripting.Actions.Calls; namespace Microsoft.Scripting.Actions { public class BoundMemberTracker : MemberTracker { - private Expression _instance; + private DynamicMetaObject _instance; private MemberTracker _tracker; private object _objInst; - public BoundMemberTracker(MemberTracker tracker, Expression instance) { + public BoundMemberTracker(MemberTracker tracker, DynamicMetaObject instance) { _tracker = tracker; _instance = instance; } @@ -44,7 +45,7 @@ public class BoundMemberTracker : MemberTracker { get { return _tracker.Name; } } - public Expression Instance { + public DynamicMetaObject Instance { get { return _instance; } @@ -62,16 +63,16 @@ public class BoundMemberTracker : MemberTracker { } } - public override Expression GetValue(Expression context, ActionBinder binder, Type type) { - return _tracker.GetBoundValue(context, binder, type, _instance); + public override DynamicMetaObject GetValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type) { + return _tracker.GetBoundValue(resolverFactory, binder, type, _instance); } public override ErrorInfo GetError(ActionBinder binder) { return _tracker.GetBoundError(binder, _instance); } - public override Expression SetValue(Expression context, ActionBinder binder, Type type, Expression value) { - return _tracker.SetBoundValue(context, binder, type, value, _instance); + public override DynamicMetaObject SetValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type, DynamicMetaObject value) { + return _tracker.SetBoundValue(resolverFactory, binder, type, value, _instance); } } } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/ConditionalBuilder.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/ConditionalBuilder.cs index 6f1c5989c4..a33e8886e2 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/ConditionalBuilder.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/ConditionalBuilder.cs @@ -48,6 +48,11 @@ class ConditionalBuilder { _bodies.Add(body); } + public void FinishCondition(DynamicMetaObject body) { + _restrictions = _restrictions.Merge(body.Restrictions); + FinishCondition(body.Expression); + } + /// /// Adds the non-conditional terminating node. /// diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.Conversions.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.Conversions.cs index 564cbfe671..a353c1ec13 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.Conversions.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.Conversions.cs @@ -14,9 +14,11 @@ * ***************************************************************************/ using System; +using System.Dynamic; using System.Linq.Expressions; using System.Reflection; -using System.Dynamic; + +using Microsoft.Scripting.Actions.Calls; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; @@ -24,9 +26,9 @@ namespace Microsoft.Scripting.Actions { using Ast = System.Linq.Expressions.Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; - + public partial class DefaultBinder : ActionBinder { - public DynamicMetaObject ConvertTo(Type toType, ConversionResultKind kind, DynamicMetaObject arg) { + public DynamicMetaObject ConvertTo(Type toType, ConversionResultKind kind, DynamicMetaObject arg, OverloadResolverFactory resolverFactory) { ContractUtils.RequiresNotNull(toType, "toType"); ContractUtils.RequiresNotNull(arg, "arg"); @@ -39,8 +41,8 @@ public partial class DefaultBinder : ActionBinder { DynamicMetaObject res = TryConvertToObject(toType, arg.Expression.Type, arg, typeRestrictions) ?? - TryAllConversions(toType, kind, arg.Expression.Type, typeRestrictions, arg) ?? - TryAllConversions(toType, kind, arg.GetLimitType(), typeRestrictions, arg) ?? + TryAllConversions(resolverFactory, toType, kind, arg.Expression.Type, typeRestrictions, arg) ?? + TryAllConversions(resolverFactory, toType, kind, arg.GetLimitType(), typeRestrictions, arg) ?? MakeErrorTarget(toType, kind, typeRestrictions, arg); if ((kind == ConversionResultKind.ExplicitTry || kind == ConversionResultKind.ImplicitTry) && toType.IsValueType) { @@ -74,14 +76,14 @@ public partial class DefaultBinder : ActionBinder { /// /// Checks if any conversions are available and if so builds the target for that conversion. /// - private DynamicMetaObject TryAllConversions(Type toType, ConversionResultKind kind, Type knownType, BindingRestrictions restrictions, DynamicMetaObject arg) { + private DynamicMetaObject TryAllConversions(OverloadResolverFactory factory, Type toType, ConversionResultKind kind, Type knownType, BindingRestrictions restrictions, DynamicMetaObject arg) { return - TryAssignableConversion(toType, knownType, restrictions, arg) ?? // known type -> known type - TryExtensibleConversion(toType, knownType, restrictions, arg) ?? // Extensible -> Extensible.Value - TryUserDefinedConversion(kind, toType, knownType, restrictions, arg) ?? // op_Implicit - TryImplicitNumericConversion(toType, knownType, restrictions, arg) ?? // op_Implicit - TryNullableConversion(toType, kind, knownType, restrictions, arg) ?? // null -> Nullable or T -> Nullable - TryNullConversion(toType, knownType, restrictions); // null -> reference type + TryAssignableConversion(toType, knownType, restrictions, arg) ?? // known type -> known type + TryExtensibleConversion(toType, knownType, restrictions, arg) ?? // Extensible -> Extensible.Value + TryUserDefinedConversion(kind, toType, knownType, restrictions, arg) ?? // op_Implicit + TryImplicitNumericConversion(toType, knownType, restrictions, arg) ?? // op_Implicit + TryNullableConversion(factory, toType, kind, knownType, restrictions, arg) ?? // null -> Nullable or T -> Nullable + TryNullConversion(toType, knownType, restrictions); // null -> reference type } /// @@ -207,7 +209,7 @@ public partial class DefaultBinder : ActionBinder { /// /// Checks if there's a conversion to/from Nullable of T. /// - private DynamicMetaObject TryNullableConversion(Type toType, ConversionResultKind kind, Type knownType, BindingRestrictions restrictions, DynamicMetaObject arg) { + private DynamicMetaObject TryNullableConversion(OverloadResolverFactory factory, Type toType, ConversionResultKind kind, Type knownType, BindingRestrictions restrictions, DynamicMetaObject arg) { if (toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(Nullable<>)) { if (knownType == typeof(DynamicNull)) { // null -> Nullable @@ -217,7 +219,7 @@ public partial class DefaultBinder : ActionBinder { } else if (kind == ConversionResultKind.ExplicitCast || kind == ConversionResultKind.ExplicitTry) { if (knownType != typeof(object)) { // when doing an explicit cast we'll do things like int -> Nullable - return MakeConvertingToTToNullableOfTTarget(toType, kind, restrictions, arg); + return MakeConvertingToTToNullableOfTTarget(factory, toType, kind, restrictions, arg); } } } @@ -410,13 +412,13 @@ public partial class DefaultBinder : ActionBinder { /// /// Helper to produce the rule for converting T to Nullable of T /// - private DynamicMetaObject MakeConvertingToTToNullableOfTTarget(Type toType, ConversionResultKind kind, BindingRestrictions restrictions, DynamicMetaObject arg) { + private DynamicMetaObject MakeConvertingToTToNullableOfTTarget(OverloadResolverFactory resolverFactory, Type toType, ConversionResultKind kind, BindingRestrictions restrictions, DynamicMetaObject arg) { Type valueType = toType.GetGenericArguments()[0]; // ConvertSelfToT -> Nullable if (kind == ConversionResultKind.ExplicitCast) { // if the conversion to T fails we just throw - Expression conversion = ConvertExpression(arg.Expression, valueType, kind, AstUtils.Constant(null, typeof(CodeContext))); + Expression conversion = ConvertExpression(arg.Expression, valueType, kind, resolverFactory); return new DynamicMetaObject( Ast.New( @@ -426,7 +428,7 @@ public partial class DefaultBinder : ActionBinder { restrictions ); } else { - Expression conversion = ConvertExpression(arg.Expression, valueType, kind, AstUtils.Constant(null, typeof(CodeContext))); + Expression conversion = ConvertExpression(arg.Expression, valueType, kind, resolverFactory); // if the conversion to T succeeds then produce the nullable, otherwise return default(retType) ParameterExpression tmp = Ast.Variable(typeof(object), "tmp"); diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.DeleteMember.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.DeleteMember.cs index 00b28399c1..25a5843342 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.DeleteMember.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.DeleteMember.cs @@ -14,40 +14,26 @@ * ***************************************************************************/ using System; -using System.Linq.Expressions; -using System.Reflection; using System.Dynamic; +using System.Reflection; + +using Microsoft.Scripting.Actions.Calls; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; + using AstUtils = Microsoft.Scripting.Ast.Utils; namespace Microsoft.Scripting.Actions { - using Ast = System.Linq.Expressions.Expression; public partial class DefaultBinder : ActionBinder { - /// - /// Builds a MetaObject for performing a member delete. Supports all built-in .NET members, the OperatorMethod - /// DeleteMember, and StrongBox instances. - /// - public DynamicMetaObject DeleteMember(string name, DynamicMetaObject target) { - ContractUtils.RequiresNotNull(name, "name"); - ContractUtils.RequiresNotNull(target, "target"); - - return DeleteMember( - name, - target, - AstUtils.Constant(null, typeof(CodeContext)) - ); - } - - public DynamicMetaObject DeleteMember(string name, DynamicMetaObject target, Expression codeContext) { + public DynamicMetaObject DeleteMember(string name, DynamicMetaObject target, OverloadResolverFactory resolutionFactory) { ContractUtils.RequiresNotNull(name, "name"); ContractUtils.RequiresNotNull(target, "target"); return MakeDeleteMemberTarget( new SetOrDeleteMemberInfo( name, - codeContext + resolutionFactory ), target.Restrict(target.GetLimitType()) ); @@ -69,7 +55,7 @@ public partial class DefaultBinder : ActionBinder { delInfo.Body.Restrictions = restrictions; - if (self == null || !MakeOperatorDeleteMemberBody(delInfo, self.Expression, type, "DeleteMember")) { + if (self == null || !MakeOperatorDeleteMemberBody(delInfo, self, type, "DeleteMember")) { MemberGroup group = GetMember(MemberRequestKind.Delete, type, delInfo.Name); if (group.Count != 0) { if (group[0].MemberType == TrackerTypes.Property) { @@ -102,21 +88,21 @@ public partial class DefaultBinder : ActionBinder { private void MakePropertyDeleteStatement(SetOrDeleteMemberInfo delInfo, DynamicMetaObject instance, MethodInfo delete) { delInfo.Body.FinishCondition( instance == null ? - MakeCallExpression(delInfo.CodeContext, delete) : - MakeCallExpression(delInfo.CodeContext, delete, instance.Expression) + MakeCallExpression(delInfo.ResolutionFactory, delete) : + MakeCallExpression(delInfo.ResolutionFactory, delete, instance) ); } /// if a member-injector is defined-on or registered-for this type call it - private bool MakeOperatorDeleteMemberBody(SetOrDeleteMemberInfo delInfo, Expression instance, Type type, string name) { + private bool MakeOperatorDeleteMemberBody(SetOrDeleteMemberInfo delInfo, DynamicMetaObject instance, Type type, string name) { MethodInfo delMem = GetMethod(type, name); if (delMem != null && delMem.IsSpecialName) { - Expression call = MakeCallExpression(delInfo.CodeContext, delMem, instance, AstUtils.Constant(delInfo.Name)); + DynamicMetaObject call = MakeCallExpression(delInfo.ResolutionFactory, delMem, instance, new DynamicMetaObject(AstUtils.Constant(delInfo.Name), BindingRestrictions.Empty, delInfo.Name)); if (delMem.ReturnType == typeof(bool)) { delInfo.Body.AddCondition( - call, + call.Expression, AstUtils.Constant(null) ); } else { @@ -133,12 +119,12 @@ public partial class DefaultBinder : ActionBinder { /// private sealed class SetOrDeleteMemberInfo { public readonly string Name; - public readonly Expression CodeContext; + public readonly OverloadResolverFactory ResolutionFactory; public readonly ConditionalBuilder Body = new ConditionalBuilder(); - public SetOrDeleteMemberInfo(string name, Expression codeContext) { + public SetOrDeleteMemberInfo(string name, OverloadResolverFactory resolutionFactory) { Name = name; - CodeContext = codeContext; + ResolutionFactory = resolutionFactory; } } } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.GetMember.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.GetMember.cs index 9f006c0ad6..6be9c28c64 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.GetMember.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.GetMember.cs @@ -14,34 +14,21 @@ * ***************************************************************************/ using System; +using System.Dynamic; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; -using System.Dynamic; + +using Microsoft.Scripting.Actions.Calls; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; + using AstUtils = Microsoft.Scripting.Ast.Utils; namespace Microsoft.Scripting.Actions { using Ast = System.Linq.Expressions.Expression; - + public partial class DefaultBinder : ActionBinder { - - /// - /// Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod - /// GetBoundMember, and StrongBox instances. - /// - /// - /// The name of the member to retrieve. This name is not processed by the DefaultBinder and - /// is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... - /// - /// - /// The MetaObject from which the member is retrieved. - /// - public DynamicMetaObject GetMember(string name, DynamicMetaObject target) { - return GetMember(name, target, AstUtils.Constant(null, typeof(CodeContext))); - } - /// /// Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod /// GetBoundMember, and StrongBox instances. @@ -53,16 +40,14 @@ public partial class DefaultBinder : ActionBinder { /// /// The MetaObject from which the member is retrieved. /// - /// - /// An expression which provides access to the CodeContext if its required for - /// accessing the member (e.g. for an extension property which takes CodeContext). By default this - /// a null CodeContext object is passed. + /// + /// Provides overload resolution and method binding for any calls which need to be performed for the GetMember. /// - public DynamicMetaObject GetMember(string name, DynamicMetaObject target, Expression codeContext) { + public DynamicMetaObject GetMember(string name, DynamicMetaObject target, OverloadResolverFactory resolverFactory) { return GetMember( name, target, - codeContext, + resolverFactory, false, null ); @@ -79,10 +64,8 @@ public partial class DefaultBinder : ActionBinder { /// /// The MetaObject from which the member is retrieved. /// - /// - /// An expression which provides access to the CodeContext if its required for - /// accessing the member (e.g. for an extension property which takes CodeContext). By default this - /// a null CodeContext object is passed. + /// + /// An OverloadResolverFactory which can be used for performing overload resolution and method binding. /// /// /// True if the operation should return Operation.Failed on failure, false if it @@ -91,15 +74,15 @@ public partial class DefaultBinder : ActionBinder { /// /// The meta object to be used if the get results in an error. /// - public DynamicMetaObject GetMember(string name, DynamicMetaObject target, Expression codeContext, bool isNoThrow, DynamicMetaObject errorSuggestion) { + public DynamicMetaObject GetMember(string name, DynamicMetaObject target, OverloadResolverFactory resolverFactory, bool isNoThrow, DynamicMetaObject errorSuggestion) { ContractUtils.RequiresNotNull(name, "name"); ContractUtils.RequiresNotNull(target, "target"); - ContractUtils.RequiresNotNull(codeContext, "codeContext"); + ContractUtils.RequiresNotNull(resolverFactory, "resolverFactory"); return MakeGetMemberTarget( new GetMemberInfo( name, - codeContext, + resolverFactory, isNoThrow, errorSuggestion ), @@ -150,11 +133,15 @@ public partial class DefaultBinder : ActionBinder { } } - Expression propSelf = self == null ? null : self.Expression; + DynamicMetaObject propSelf = self == null ? null : self; // if lookup failed try the strong-box type if available. if (members.Count == 0 && typeof(IStrongBox).IsAssignableFrom(type) && propSelf != null) { // properties/fields need the direct value, methods hold onto the strong box. - propSelf = Ast.Field(AstUtils.Convert(propSelf, type), type.GetField("Value")); + propSelf = new DynamicMetaObject( + Ast.Field(AstUtils.Convert(propSelf.Expression, type), type.GetField("Value")), + propSelf.Restrictions, + ((IStrongBox)propSelf.Value).Value + ); type = type.GetGenericArguments()[0]; @@ -171,7 +158,7 @@ public partial class DefaultBinder : ActionBinder { return getMemInfo.Body.GetMetaObject(target); } - private void MakeBodyHelper(GetMemberInfo getMemInfo, DynamicMetaObject self, Expression propSelf, Type type, MemberGroup members) { + private void MakeBodyHelper(GetMemberInfo getMemInfo, DynamicMetaObject self, DynamicMetaObject propSelf, Type type, MemberGroup members) { if (self != null) { MakeOperatorGetMemberBody(getMemInfo, propSelf, type, "GetCustomMember"); } @@ -186,7 +173,7 @@ public partial class DefaultBinder : ActionBinder { } } - private void MakeSuccessfulMemberAccess(GetMemberInfo getMemInfo, DynamicMetaObject self, Expression propSelf, Type type, MemberGroup members, TrackerTypes memberType) { + private void MakeSuccessfulMemberAccess(GetMemberInfo getMemInfo, DynamicMetaObject self, DynamicMetaObject propSelf, Type type, MemberGroup members, TrackerTypes memberType) { switch (memberType) { case TrackerTypes.TypeGroup: case TrackerTypes.Type: @@ -194,7 +181,7 @@ public partial class DefaultBinder : ActionBinder { break; case TrackerTypes.Method: // turn into a MethodGroup - MakeGenericBodyWorker(getMemInfo, type, ReflectionCache.GetMethodGroup(getMemInfo.Name, members), self == null ? null : self.Expression); + MakeGenericBodyWorker(getMemInfo, type, ReflectionCache.GetMethodGroup(getMemInfo.Name, members), self); break; case TrackerTypes.Event: case TrackerTypes.Field: @@ -216,7 +203,7 @@ public partial class DefaultBinder : ActionBinder { } } - private void MakeGenericBody(GetMemberInfo getMemInfo, Type type, MemberGroup members, Expression instance) { + private void MakeGenericBody(GetMemberInfo getMemInfo, Type type, MemberGroup members, DynamicMetaObject instance) { MemberTracker bestMember = members[0]; if (members.Count > 1) { // if we were given multiple members pick the member closest to the type... @@ -249,15 +236,15 @@ public partial class DefaultBinder : ActionBinder { typeTracker = TypeGroup.UpdateTypeEntity(typeTracker, (TypeTracker)members[i]); } - getMemInfo.Body.FinishCondition(typeTracker.GetValue(getMemInfo.CodeContext, this, type)); + getMemInfo.Body.FinishCondition(typeTracker.GetValue(getMemInfo.ResolutionFactory, this, type)); } - private void MakeGenericBodyWorker(GetMemberInfo getMemInfo, Type type, MemberTracker tracker, Expression instance) { + private void MakeGenericBodyWorker(GetMemberInfo getMemInfo, Type type, MemberTracker tracker, DynamicMetaObject instance) { if (instance != null) { tracker = tracker.BindToInstance(instance); } - Expression val = tracker.GetValue(getMemInfo.CodeContext, this, type); + DynamicMetaObject val = tracker.GetValue(getMemInfo.ResolutionFactory, this, type); if (val != null) { getMemInfo.Body.FinishCondition(val); @@ -272,7 +259,7 @@ public partial class DefaultBinder : ActionBinder { } /// if a member-injector is defined-on or registered-for this type call it - private void MakeOperatorGetMemberBody(GetMemberInfo getMemInfo, Expression instance, Type type, string name) { + private void MakeOperatorGetMemberBody(GetMemberInfo getMemInfo, DynamicMetaObject instance, Type type, string name) { MethodInfo getMem = GetMethod(type, name); if (getMem != null && getMem.IsSpecialName) { ParameterExpression tmp = Ast.Variable(typeof(object), "getVal"); @@ -283,11 +270,19 @@ public partial class DefaultBinder : ActionBinder { Ast.Assign( tmp, MakeCallExpression( - getMemInfo.CodeContext, + getMemInfo.ResolutionFactory, getMem, - AstUtils.Convert(instance, type), - AstUtils.Constant(getMemInfo.Name) - ) + new DynamicMetaObject( + Expression.Convert(instance.Expression, type), + instance.Restrictions, + instance.Value + ), + new DynamicMetaObject( + Expression.Constant(getMemInfo.Name), + BindingRestrictions.Empty, + getMemInfo.Name + ) + ).Expression ), Ast.Field(null, typeof(OperationFailed).GetField("Value")) ), @@ -318,14 +313,14 @@ public partial class DefaultBinder : ActionBinder { /// private sealed class GetMemberInfo { public readonly string Name; - public readonly Expression CodeContext; + public readonly OverloadResolverFactory ResolutionFactory; public readonly bool IsNoThrow; public readonly ConditionalBuilder Body = new ConditionalBuilder(); public readonly DynamicMetaObject ErrorSuggestion; - public GetMemberInfo(string name, Expression codeContext, bool noThrow, DynamicMetaObject errorSuggestion) { + public GetMemberInfo(string name, OverloadResolverFactory resolutionFactory, bool noThrow, DynamicMetaObject errorSuggestion) { Name = name; - CodeContext = codeContext; + ResolutionFactory = resolutionFactory; IsNoThrow = noThrow; ErrorSuggestion = errorSuggestion; } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.Operations.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.Operations.cs index 638ee7ba32..98e1b8043f 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.Operations.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.Operations.cs @@ -57,7 +57,7 @@ private enum IndexType { /// public DynamicMetaObject GetIndex(OverloadResolverFactory resolverFactory, DynamicMetaObject[] args) { if (args[0].GetLimitType().IsArray) { - return MakeArrayIndexRule(IndexType.Get, args); + return MakeArrayIndexRule(resolverFactory, IndexType.Get, args); } return MakeMethodIndexRule(IndexType.Get, resolverFactory, args); @@ -73,7 +73,7 @@ private enum IndexType { /// public DynamicMetaObject SetIndex(OverloadResolverFactory resolverFactory, DynamicMetaObject[] args) { if (args[0].LimitType.IsArray) { - return MakeArrayIndexRule(IndexType.Set, args); + return MakeArrayIndexRule(resolverFactory, IndexType.Set, args); } return MakeMethodIndexRule(IndexType.Set, resolverFactory, args); @@ -408,8 +408,6 @@ private enum IndexType { StringBuilder res = new StringBuilder(); string comma = ""; foreach (ParameterInfo param in mb.GetParameters()) { - if (param.ParameterType == typeof(CodeContext)) continue; - res.Append(comma); res.Append(param.ParameterType.Name); res.Append(" "); @@ -484,7 +482,7 @@ private enum IndexType { return null; } - private DynamicMetaObject MakeArrayIndexRule(IndexType oper, DynamicMetaObject[] args) { + private DynamicMetaObject MakeArrayIndexRule(OverloadResolverFactory factory, IndexType oper, DynamicMetaObject[] args) { if (CanConvertFrom(GetArgType(args, 1), typeof(int), false, NarrowingLevel.All)) { BindingRestrictions restrictions = BindingRestrictionsHelpers.GetRuntimeTypeRestriction(args[0].Expression, args[0].GetLimitType()).Merge(BindingRestrictions.Combine(args)); @@ -492,7 +490,7 @@ private enum IndexType { return new DynamicMetaObject( Ast.ArrayAccess( args[0].Expression, - ConvertIfNeeded(args[1].Expression, typeof(int)) + ConvertIfNeeded(factory, args[1].Expression, typeof(int)) ), restrictions ); @@ -501,9 +499,9 @@ private enum IndexType { Ast.Assign( Ast.ArrayAccess( args[0].Expression, - ConvertIfNeeded(args[1].Expression, typeof(int)) + ConvertIfNeeded(factory, args[1].Expression, typeof(int)) ), - ConvertIfNeeded(args[2].Expression, args[0].GetLimitType().GetElementType()) + ConvertIfNeeded(factory, args[2].Expression, args[0].GetLimitType().GetElementType()) ), restrictions.Merge(args[1].Restrictions) ); @@ -590,11 +588,11 @@ private enum IndexType { } } - private Expression ConvertIfNeeded(Expression expression, Type type) { + private Expression ConvertIfNeeded(OverloadResolverFactory factory, Expression expression, Type type) { Assert.NotNull(expression, type); if (expression.Type != type) { - return ConvertExpression(expression, type, ConversionResultKind.ExplicitCast, AstUtils.Constant(null, typeof(CodeContext))); + return ConvertExpression(expression, type, ConversionResultKind.ExplicitCast, factory); } return expression; } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.SetMember.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.SetMember.cs index a14c80e3d9..4056c5835e 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.SetMember.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.SetMember.cs @@ -14,38 +14,23 @@ * ***************************************************************************/ using System; +using System.Diagnostics; +using System.Dynamic; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; -using System.Dynamic; + +using Microsoft.Scripting.Actions.Calls; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; + using AstUtils = Microsoft.Scripting.Ast.Utils; namespace Microsoft.Scripting.Actions { using Ast = System.Linq.Expressions.Expression; - using System.Diagnostics; - - public partial class DefaultBinder : ActionBinder { - /// - /// Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod - /// GetBoundMember, and StrongBox instances. - /// - /// - /// The name of the member to retrieve. This name is not processed by the DefaultBinder and - /// is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... - /// - /// - /// The MetaObject from which the member is retrieved. - /// - /// - /// The value being assigned to the target member. - /// - public DynamicMetaObject SetMember(string name, DynamicMetaObject target, DynamicMetaObject value) { - return SetMember(name, target, value, AstUtils.Constant(null, typeof(CodeContext))); - } - + + public partial class DefaultBinder : ActionBinder { /// /// Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod /// GetBoundMember, and StrongBox instances. @@ -60,19 +45,17 @@ public partial class DefaultBinder : ActionBinder { /// /// The value being assigned to the target member. /// - /// - /// An expression which provides access to the CodeContext if its required for - /// accessing the member (e.g. for an extension property which takes CodeContext). By default this - /// a null CodeContext object is passed. + /// + /// rovides overload resolution and method binding for any calls which need to be performed for the SetMember. /// - public DynamicMetaObject SetMember(string name, DynamicMetaObject target, DynamicMetaObject value, Expression codeContext) { + public DynamicMetaObject SetMember(string name, DynamicMetaObject target, DynamicMetaObject value, OverloadResolverFactory resolverFactory) { ContractUtils.RequiresNotNull(name, "name"); ContractUtils.RequiresNotNull(target, "target"); ContractUtils.RequiresNotNull(value, "value"); - ContractUtils.RequiresNotNull(codeContext, "codeContext"); + ContractUtils.RequiresNotNull(resolverFactory, "resolverFactory"); return MakeSetMemberTarget( - new SetOrDeleteMemberInfo(name, codeContext), + new SetOrDeleteMemberInfo(name, resolverFactory), target, value ); @@ -125,12 +108,12 @@ public partial class DefaultBinder : ActionBinder { case TrackerTypes.Type: case TrackerTypes.Constructor: memInfo.Body.FinishCondition( - MakeError(MakeReadOnlyMemberError(type, memInfo.Name), typeof(object)) + MakeError(MakeReadOnlyMemberError(type, memInfo.Name), BindingRestrictions.Empty, typeof(object)) ); break; case TrackerTypes.Event: memInfo.Body.FinishCondition( - MakeError(MakeEventValidation(members, self == null ? null : self.Expression, value.Expression, memInfo.CodeContext), typeof(object)) + MakeError(MakeEventValidation(members, self, value, memInfo.ResolutionFactory), BindingRestrictions.Empty, typeof(object)) ); break; case TrackerTypes.Field: @@ -149,7 +132,7 @@ public partial class DefaultBinder : ActionBinder { } memInfo.Body.FinishCondition( - MakeError(MakeMissingMemberErrorForAssign(type, self, memInfo.Name), typeof(object)) + MakeError(MakeMissingMemberErrorForAssign(type, self, memInfo.Name), BindingRestrictions.Empty, typeof(object)) ); break; default: @@ -162,10 +145,10 @@ public partial class DefaultBinder : ActionBinder { private void MakeGenericBody(SetOrDeleteMemberInfo memInfo, DynamicMetaObject instance, DynamicMetaObject target, Type type, MemberTracker tracker) { if (instance != null) { - tracker = tracker.BindToInstance(instance.Expression); + tracker = tracker.BindToInstance(instance); } - Expression val = tracker.SetValue(memInfo.CodeContext, this, type, target.Expression); + DynamicMetaObject val = tracker.SetValue(memInfo.ResolutionFactory, this, type, target); if (val != null) { memInfo.Body.FinishCondition(val); @@ -197,8 +180,8 @@ public partial class DefaultBinder : ActionBinder { MakeStaticPropertyInstanceAccessError( info, true, - instance == null ? null : instance.Expression, - target.Expression + instance, + target ), typeof(object) ) @@ -206,7 +189,7 @@ public partial class DefaultBinder : ActionBinder { } else if (info.IsStatic && info.DeclaringType != targetType) { memInfo.Body.FinishCondition( MakeError( - MakeStaticAssignFromDerivedTypeError(targetType, instance, info, target.Expression, memInfo.CodeContext), + MakeStaticAssignFromDerivedTypeError(targetType, instance, info, target, memInfo.ResolutionFactory), typeof(object) ) ); @@ -224,7 +207,7 @@ public partial class DefaultBinder : ActionBinder { target.Expression, setter.GetParameters()[0].ParameterType, ConversionResultKind.ExplicitCast, - memInfo.CodeContext + memInfo.ResolutionFactory ) ), Ast.Constant(null) @@ -233,7 +216,7 @@ public partial class DefaultBinder : ActionBinder { } else { memInfo.Body.FinishCondition( MakeReturnValue( - MakeCallExpression(memInfo.CodeContext, setter, instance.Expression, target.Expression), + MakeCallExpression(memInfo.ResolutionFactory, setter, instance, target), target ) ); @@ -251,7 +234,7 @@ public partial class DefaultBinder : ActionBinder { target.Expression, setter.GetParameters()[0].ParameterType, ConversionResultKind.ExplicitCast, - memInfo.CodeContext + memInfo.ResolutionFactory ), typeof(object) ), @@ -299,7 +282,7 @@ public partial class DefaultBinder : ActionBinder { } else if (field.IsStatic && targetType != field.DeclaringType) { memInfo.Body.FinishCondition( MakeError( - MakeStaticAssignFromDerivedTypeError(targetType, instance, field, target.Expression, memInfo.CodeContext), + MakeStaticAssignFromDerivedTypeError(targetType, instance, field, target, memInfo.ResolutionFactory), typeof(object) ) ); @@ -325,7 +308,7 @@ public partial class DefaultBinder : ActionBinder { AstUtils.Convert(instance.Expression, field.DeclaringType), field.Field ), - ConvertExpression(target.Expression, field.FieldType, ConversionResultKind.ExplicitCast, memInfo.CodeContext) + ConvertExpression(target.Expression, field.FieldType, ConversionResultKind.ExplicitCast, memInfo.ResolutionFactory) ), target ) @@ -349,6 +332,16 @@ public partial class DefaultBinder : ActionBinder { } } + private DynamicMetaObject MakeReturnValue(DynamicMetaObject expression, DynamicMetaObject target) { + return new DynamicMetaObject( + Ast.Block( + expression.Expression, + Expression.Convert(target.Expression, typeof(object)) + ), + target.Restrictions.Merge(expression.Restrictions) + ); + } + private Expression MakeReturnValue(Expression expression, DynamicMetaObject target) { return Ast.Block( expression, @@ -364,9 +357,15 @@ public partial class DefaultBinder : ActionBinder { ParameterExpression tmp = Ast.Variable(target.Expression.Type, "setValue"); memInfo.Body.AddVariable(tmp); - Expression call = MakeCallExpression(memInfo.CodeContext, setMem, AstUtils.Convert(self.Expression, type), AstUtils.Constant(memInfo.Name), tmp); + var callMo = MakeCallExpression( + memInfo.ResolutionFactory, + setMem, + self.Clone(AstUtils.Convert(self.Expression, type)), + new DynamicMetaObject(AstUtils.Constant(memInfo.Name), BindingRestrictions.Empty, memInfo.Name), + target.Clone(tmp) + ); - call = Ast.Block(Ast.Assign(tmp, target.Expression), call); + var call = Ast.Block(Ast.Assign(tmp, target.Expression), callMo.Expression); if (setMem.ReturnType == typeof(bool)) { memInfo.Body.AddCondition( diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.cs index 48fd4f995b..321d4deec8 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/DefaultBinder.cs @@ -39,17 +39,6 @@ protected DefaultBinder(ScriptDomainManager manager) : base(manager) { } - protected static CodeContext ExtractCodeContext(object[] args, out object[] extracted) { - CodeContext cc; - if (args.Length > 0 && (cc = args[0] as CodeContext) != null) { - extracted = ArrayUtils.ShiftLeft(args, 1); - } else { - cc = null; - extracted = args; - } - return cc; - } - /// /// Provides a way for the binder to provide a custom error message when lookup fails. Just /// doing this for the time being until we get a more robust error return mechanism. @@ -63,7 +52,7 @@ protected DefaultBinder(ScriptDomainManager manager) /// /// The default implementation allows access to the fields or properties using reflection. /// - public virtual ErrorInfo MakeNonPublicMemberGetError(Expression codeContext, MemberTracker member, Type type, Expression instance) { + public virtual ErrorInfo MakeNonPublicMemberGetError(OverloadResolverFactory resolverFactory, MemberTracker member, Type type, DynamicMetaObject instance) { switch (member.MemberType) { case TrackerTypes.Field: FieldTracker ft = (FieldTracker)member; @@ -72,14 +61,14 @@ protected DefaultBinder(ScriptDomainManager manager) Ast.Call( AstUtils.Convert(AstUtils.Constant(ft.Field), typeof(FieldInfo)), typeof(FieldInfo).GetMethod("GetValue"), - AstUtils.Convert(instance, typeof(object)) + AstUtils.Convert(instance.Expression, typeof(object)) ) ); case TrackerTypes.Property: PropertyTracker pt = (PropertyTracker)member; return ErrorInfo.FromValueNoError( - MemberTracker.FromMemberInfo(pt.GetGetMethod(true)).Call(codeContext, this, instance) + MemberTracker.FromMemberInfo(pt.GetGetMethod(true)).Call(resolverFactory, this, instance).Expression ); default: throw new InvalidOperationException(); @@ -99,7 +88,7 @@ protected DefaultBinder(ScriptDomainManager manager) ); } - public virtual ErrorInfo MakeEventValidation(MemberGroup members, Expression eventObject, Expression value, Expression codeContext) { + public virtual ErrorInfo MakeEventValidation(MemberGroup members, DynamicMetaObject eventObject, DynamicMetaObject value, OverloadResolverFactory resolverFactory) { EventTracker ev = (EventTracker)members[0]; // handles in place addition of events - this validates the user did the right thing. @@ -107,29 +96,29 @@ protected DefaultBinder(ScriptDomainManager manager) Expression.Call( typeof(BinderOps).GetMethod("SetEvent"), AstUtils.Constant(ev), - value + value.Expression ) ); } - public static Expression MakeError(ErrorInfo error, Type type) { + public static DynamicMetaObject MakeError(ErrorInfo error, Type type) { + return MakeError(error, BindingRestrictions.Empty, type); + } + + public static DynamicMetaObject MakeError(ErrorInfo error, BindingRestrictions restrictions, Type type) { switch (error.Kind) { case ErrorInfoKind.Error: // error meta objecT? - return AstUtils.Convert(error.Expression, type); + return new DynamicMetaObject(AstUtils.Convert(error.Expression, type), restrictions); case ErrorInfoKind.Exception: - return AstUtils.Convert(Expression.Throw(error.Expression), type); + return new DynamicMetaObject(AstUtils.Convert(Expression.Throw(error.Expression), type), restrictions); case ErrorInfoKind.Success: - return error.Expression; + return new DynamicMetaObject(error.Expression, restrictions); default: throw new InvalidOperationException(); } } - public static DynamicMetaObject MakeError(ErrorInfo error, BindingRestrictions restrictions, Type type) { - return new DynamicMetaObject(MakeError(error, type), restrictions); - } - private static Expression MakeAmbiguousMatchError(MemberGroup members) { StringBuilder sb = new StringBuilder(); foreach (MemberTracker mi in members) { @@ -194,7 +183,7 @@ protected DefaultBinder(ScriptDomainManager manager) } while (curType != null); return null; - } + } } } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/ErrorInfo.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/ErrorInfo.cs index c63ce62b42..45640363fb 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/ErrorInfo.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/ErrorInfo.cs @@ -80,23 +80,6 @@ public sealed class ErrorInfo { return new ErrorInfo(resultValue, ErrorInfoKind.Success); } - /// - /// Internal helper to produce the actual expression used for the error when emitting - /// the error into a rule. - /// - public Expression MakeErrorForRule(RuleBuilder rule, ActionBinder binder) { - switch (_kind) { - case ErrorInfoKind.Error: - rule.IsError = true; - return rule.MakeReturn(binder, _value); - case ErrorInfoKind.Success: - return rule.MakeReturn(binder, _value); - case ErrorInfoKind.Exception: - return rule.MakeError(_value); - default: throw new InvalidOperationException(); - } - } - public ErrorInfoKind Kind { get { return _kind; diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/EventTracker.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/EventTracker.cs index ee5861ecb0..4360fa2f25 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/EventTracker.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/EventTracker.cs @@ -14,17 +14,19 @@ * ***************************************************************************/ using System; +using System.Collections.Generic; using System.Diagnostics; -using System.Linq.Expressions; +using System.Dynamic; using System.Reflection; -using Microsoft.Contracts; -using System.Collections.Generic; -using Microsoft.Scripting.Utils; -using Microsoft.Scripting.Runtime; using System.Runtime.InteropServices; -using Microsoft.Scripting.Generation; using System.Threading; +using Microsoft.Contracts; +using Microsoft.Scripting.Actions.Calls; +using Microsoft.Scripting.Generation; +using Microsoft.Scripting.Runtime; +using Microsoft.Scripting.Utils; + namespace Microsoft.Scripting.Actions { public class EventTracker : MemberTracker { // For each instance of the class that declares the event there is a list of pairs in a table @@ -102,11 +104,11 @@ public class EventTracker : MemberTracker { } } - protected internal override Expression GetBoundValue(Expression context, ActionBinder binder, Type type, Expression instance) { + protected internal override DynamicMetaObject GetBoundValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type, DynamicMetaObject instance) { return binder.ReturnMemberTracker(type, new BoundMemberTracker(this, instance)); } - public override MemberTracker BindToInstance(Expression instance) { + public override MemberTracker BindToInstance(DynamicMetaObject instance) { if (IsStatic) { return this; } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/FieldTracker.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/FieldTracker.cs index 18709c3718..060492d3a9 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/FieldTracker.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/FieldTracker.cs @@ -15,10 +15,13 @@ using System; using System.Diagnostics; -using System.Linq.Expressions; +using System.Dynamic; using System.Reflection; + using Microsoft.Contracts; +using Microsoft.Scripting.Actions.Calls; using Microsoft.Scripting.Utils; + using AstUtils = Microsoft.Scripting.Ast.Utils; namespace Microsoft.Scripting.Actions { @@ -87,9 +90,12 @@ public class FieldTracker : MemberTracker { #region Public expression builders - public override Expression GetValue(Expression context, ActionBinder binder, Type type) { + public override DynamicMetaObject GetValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type) { if (Field.IsLiteral) { - return AstUtils.Constant(Field.GetValue(null), typeof(object)); + return new DynamicMetaObject( + AstUtils.Constant(Field.GetValue(null), typeof(object)), + BindingRestrictions.Empty + ); } if (!IsStatic) { @@ -102,13 +108,19 @@ public class FieldTracker : MemberTracker { } if (IsPublic && DeclaringType.IsPublic) { - return Ast.Convert(Ast.Field(null, Field), typeof(object)); + return new DynamicMetaObject( + Ast.Convert(Ast.Field(null, Field), typeof(object)), + BindingRestrictions.Empty + ); } - return Ast.Call( - AstUtils.Convert(AstUtils.Constant(Field), typeof(FieldInfo)), - typeof(FieldInfo).GetMethod("GetValue"), - AstUtils.Constant(null) + return new DynamicMetaObject( + Ast.Call( + AstUtils.Convert(AstUtils.Constant(Field), typeof(FieldInfo)), + typeof(FieldInfo).GetMethod("GetValue"), + AstUtils.Constant(null) + ), + BindingRestrictions.Empty ); } @@ -124,21 +136,24 @@ public class FieldTracker : MemberTracker { #region Internal expression builders - protected internal override Expression GetBoundValue(Expression context, ActionBinder binder, Type type, Expression instance) { + protected internal override DynamicMetaObject GetBoundValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type, DynamicMetaObject instance) { if (IsPublic && DeclaringType.IsVisible) { - return AstUtils.Convert( - Ast.Field( - AstUtils.Convert(instance, Field.DeclaringType), - Field + return new DynamicMetaObject( + AstUtils.Convert( + Ast.Field( + AstUtils.Convert(instance.Expression, Field.DeclaringType), + Field + ), + typeof(object) ), - typeof(object) + BindingRestrictions.Empty ); } - return DefaultBinder.MakeError(((DefaultBinder)binder).MakeNonPublicMemberGetError(context, this, type, instance), typeof(object)); + return DefaultBinder.MakeError(((DefaultBinder)binder).MakeNonPublicMemberGetError(resolverFactory, this, type, instance), BindingRestrictions.Empty, typeof(object)); } - public override MemberTracker BindToInstance(Expression instance) { + public override MemberTracker BindToInstance(DynamicMetaObject instance) { if (IsStatic) return this; return new BoundMemberTracker(this, instance); diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/MemberTracker.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/MemberTracker.cs index 608abb290f..c3e1530f67 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/MemberTracker.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/MemberTracker.cs @@ -15,8 +15,10 @@ using System; using System.Collections.Generic; -using System.Linq.Expressions; +using System.Dynamic; using System.Reflection; + +using Microsoft.Scripting.Actions.Calls; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; @@ -137,7 +139,7 @@ class MemberKey { /// Returns null if it's an error to get the value. The caller can then call GetErrorForGet to get /// the correct error Expression (or null if they should provide a default). /// - public virtual Expression GetValue(Expression context, ActionBinder binder, Type type) { + public virtual DynamicMetaObject GetValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type) { return binder.ReturnMemberTracker(type, this); } @@ -147,7 +149,7 @@ class MemberKey { /// Returns null if it's an error to assign to. The caller can then call GetErrorForSet to /// get the correct error Expression (or null if a default error should be provided). /// - public virtual Expression SetValue(Expression context, ActionBinder binder, Type type, Expression value) { + public virtual DynamicMetaObject SetValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type, DynamicMetaObject value) { return null; } @@ -158,7 +160,7 @@ class MemberKey { /// GetErrorsForDoCall to get the correct error Expression (or null if a default error should be provided). /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Call")] // TODO: fix - internal virtual Expression Call(Expression context, ActionBinder binder, params Expression[] arguments) { + internal virtual DynamicMetaObject Call(OverloadResolverFactory resolverFactory, ActionBinder binder, params DynamicMetaObject[] arguments) { return null; } @@ -180,7 +182,7 @@ class MemberKey { /// /// A null return value indicates that the default error message should be provided by the caller. /// - public virtual ErrorInfo GetBoundError(ActionBinder binder, Expression instance) { + public virtual ErrorInfo GetBoundError(ActionBinder binder, DynamicMetaObject instance) { return null; } @@ -188,16 +190,16 @@ class MemberKey { /// Helper for getting values that have been bound. Called from BoundMemberTracker. Custom member /// trackers can override this to provide their own behaviors when bound to an instance. /// - protected internal virtual Expression GetBoundValue(Expression context, ActionBinder binder, Type type, Expression instance) { - return GetValue(context, binder, type); + protected internal virtual DynamicMetaObject GetBoundValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type, DynamicMetaObject instance) { + return GetValue(resolverFactory, binder, type); } /// /// Helper for setting values that have been bound. Called from BoundMemberTracker. Custom member /// trackers can override this to provide their own behaviors when bound to an instance. /// - protected internal virtual Expression SetBoundValue(Expression context, ActionBinder binder, Type type, Expression value, Expression instance) { - return SetValue(context, binder, type, instance); + protected internal virtual DynamicMetaObject SetBoundValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type, DynamicMetaObject value, DynamicMetaObject instance) { + return SetValue(resolverFactory, binder, type, instance); } /// @@ -207,7 +209,7 @@ class MemberKey { /// field results in a new BoundMemberTracker which will get GetBoundValue/SetBoundValue to pass the /// instance through. /// - public virtual MemberTracker BindToInstance(Expression instance) { + public virtual MemberTracker BindToInstance(DynamicMetaObject instance) { return this; } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/MethodGroup.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/MethodGroup.cs index 9183c0bc31..7d36ae10c2 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/MethodGroup.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/MethodGroup.cs @@ -16,10 +16,12 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Linq.Expressions; +using System.Dynamic; using System.Reflection; using System.Threading; + using Microsoft.Contracts; +using Microsoft.Scripting.Actions.Calls; namespace Microsoft.Scripting.Actions { /// @@ -84,11 +86,11 @@ public class MethodGroup : MemberTracker { return methods; } - public override Expression GetValue(Expression context, ActionBinder binder, Type type) { - return base.GetValue(context, binder, type); + public override DynamicMetaObject GetValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type) { + return base.GetValue(resolverFactory, binder, type); } - public override MemberTracker BindToInstance(Expression instance) { + public override MemberTracker BindToInstance(DynamicMetaObject instance) { if (ContainsInstance) { return new BoundMemberTracker(this, instance); } @@ -96,7 +98,7 @@ public class MethodGroup : MemberTracker { return this; } - protected internal override Expression GetBoundValue(Expression context, ActionBinder binder, Type type, Expression instance) { + protected internal override DynamicMetaObject GetBoundValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type, DynamicMetaObject instance) { return binder.ReturnMemberTracker(type, BindToInstance(instance)); } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/MethodTracker.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/MethodTracker.cs index c4e78349a5..3ce067616d 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/MethodTracker.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/MethodTracker.cs @@ -14,15 +14,18 @@ * ***************************************************************************/ using System; -using System.Linq.Expressions; +using System.Dynamic; using System.Reflection; -using Microsoft.Scripting.Utils; + using Microsoft.Contracts; +using Microsoft.Scripting.Actions.Calls; +using Microsoft.Scripting.Utils; + using AstUtils = Microsoft.Scripting.Ast.Utils; namespace Microsoft.Scripting.Actions { using Ast = System.Linq.Expressions.Expression; - + public class MethodTracker : MemberTracker { private readonly MethodInfo _method; private readonly bool _isStatic; @@ -74,7 +77,7 @@ public class MethodTracker : MemberTracker { return _method.ToString(); } - public override MemberTracker BindToInstance(Expression instance) { + public override MemberTracker BindToInstance(DynamicMetaObject instance) { if (IsStatic) { return this; } @@ -82,38 +85,46 @@ public class MethodTracker : MemberTracker { return new BoundMemberTracker(this, instance); } - protected internal override Expression GetBoundValue(Expression context, ActionBinder binder, Type type, Expression instance) { + protected internal override DynamicMetaObject GetBoundValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type, DynamicMetaObject instance) { return binder.ReturnMemberTracker(type, BindToInstance(instance)); } - internal override System.Linq.Expressions.Expression Call(Expression context, ActionBinder binder, params Expression[] arguments) { + internal override DynamicMetaObject Call(OverloadResolverFactory resolverFactory, ActionBinder binder, params DynamicMetaObject[] arguments) { if (Method.IsPublic && Method.DeclaringType.IsVisible) { - // TODO: Need to use MethodBinder in here to make this right. - return binder.MakeCallExpression(context, Method, arguments); + return binder.MakeCallExpression(resolverFactory, Method, arguments); } //methodInfo.Invoke(obj, object[] params) if (Method.IsStatic) { - return Ast.Convert( - Ast.Call( - AstUtils.Constant(Method), - typeof(MethodInfo).GetMethod("Invoke", new Type[] { typeof(object), typeof(object[]) }), - AstUtils.Constant(null), - AstUtils.NewArrayHelper(typeof(object), arguments) - ), - Method.ReturnType); + return new DynamicMetaObject( + Ast.Convert( + Ast.Call( + AstUtils.Constant(Method), + typeof(MethodInfo).GetMethod("Invoke", new Type[] { typeof(object), typeof(object[]) }), + AstUtils.Constant(null), + AstUtils.NewArrayHelper(typeof(object), ArrayUtils.ConvertAll(arguments, x => x.Expression)) + ), + Method.ReturnType + ), + BindingRestrictions.Empty + ) + ; } if (arguments.Length == 0) throw Error.NoInstanceForCall(); - return Ast.Convert( - Ast.Call( - AstUtils.Constant(Method), - typeof(MethodInfo).GetMethod("Invoke", new Type[] { typeof(object), typeof(object[]) }), - arguments[0], - AstUtils.NewArrayHelper(typeof(object), ArrayUtils.RemoveFirst(arguments)) + return new DynamicMetaObject( + Ast.Convert( + Ast.Call( + AstUtils.Constant(Method), + typeof(MethodInfo).GetMethod("Invoke", new Type[] { typeof(object), typeof(object[]) }), + arguments[0].Expression, + AstUtils.NewArrayHelper(typeof(object), ArrayUtils.ConvertAll(ArrayUtils.RemoveFirst(arguments), x => x.Expression)) + ), + Method.ReturnType ), - Method.ReturnType); + BindingRestrictions.Empty + ); } } } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/NamespaceTracker.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/NamespaceTracker.cs index d032eb29d7..18ae1cf72f 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/NamespaceTracker.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/NamespaceTracker.cs @@ -392,22 +392,25 @@ public class NamespaceTracker : MemberTracker, IAttributesCollection, IMembersLi lock (_topPackage.HierarchyLock) { List res = new List(); - foreach (string s in _dict.Keys) { - res.Add(s); - } + return (ICollection)AddKeys(res); + } + } + } - foreach (KeyValuePair kvp in _typeNames) { - foreach (string typeName in kvp.Value.GetNormalizedTypeNames()) { - if (!res.Contains(typeName)) { - res.Add(typeName); - } - } - } + private IList AddKeys(IList res) { + foreach (string s in _dict.Keys) { + res.Add(s); + } - res.Sort(); - return res; + foreach (KeyValuePair kvp in _typeNames) { + foreach (string typeName in kvp.Value.GetNormalizedTypeNames()) { + if (!res.Contains(typeName)) { + res.Add(typeName); + } } } + + return res; } #endregion @@ -545,8 +548,16 @@ internal class TypeNames { #region IMembersList Members - public IList GetMemberNames(CodeContext context) { - return (IList)Keys; + public IList GetMemberNames() { + LoadNamespaces(); + + lock (_topPackage.HierarchyLock) { + + List res = new List(); + AddKeys(res); + res.Sort(); + return res; + } } #endregion diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/PropertyTracker.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/PropertyTracker.cs index 634958f546..91bc47a59e 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/PropertyTracker.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/PropertyTracker.cs @@ -14,11 +14,11 @@ * ***************************************************************************/ using System; -using System.Linq.Expressions; +using System.Dynamic; using System.Reflection; + +using Microsoft.Scripting.Actions.Calls; using Microsoft.Scripting.Generation; -using Microsoft.Scripting.Runtime; -using AstUtils = Microsoft.Scripting.Ast.Utils; namespace Microsoft.Scripting.Actions { @@ -57,7 +57,7 @@ public abstract class PropertyTracker : MemberTracker { #region Public expression builders - public override Expression GetValue(Expression context, ActionBinder binder, Type type) { + public override DynamicMetaObject GetValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type) { if (!IsStatic || GetIndexParameters().Length > 0) { // need to bind to a value or parameters to get the value. return binder.ReturnMemberTracker(type, this); @@ -70,11 +70,11 @@ public abstract class PropertyTracker : MemberTracker { } if (getter.IsPublic && getter.DeclaringType.IsPublic) { - return AstUtils.Convert(binder.MakeCallExpression(context, getter), typeof(object)); + return binder.MakeCallExpression(resolverFactory, getter); } // private binding is just a call to the getter method... - return MemberTracker.FromMemberInfo(getter).Call(context, binder); + return MemberTracker.FromMemberInfo(getter).Call(resolverFactory, binder); } public override ErrorInfo GetError(ActionBinder binder) { @@ -95,7 +95,7 @@ public abstract class PropertyTracker : MemberTracker { #region Internal expression builders - protected internal override Expression GetBoundValue(Expression context, ActionBinder binder, Type type, Expression instance) { + protected internal override DynamicMetaObject GetBoundValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type, DynamicMetaObject instance) { if (instance != null && IsStatic) { return null; } @@ -114,14 +114,14 @@ public abstract class PropertyTracker : MemberTracker { getter = CompilerHelpers.TryGetCallableMethod(getter); if (binder.PrivateBinding || CompilerHelpers.IsVisible(getter)) { - return AstUtils.Convert(binder.MakeCallExpression(context, getter, instance), typeof(object)); + return ((DefaultBinder)binder).MakeCallExpression(resolverFactory, getter, instance); } // private binding is just a call to the getter method... - return DefaultBinder.MakeError(((DefaultBinder)binder).MakeNonPublicMemberGetError(context, this, type, instance), typeof(object)); + return DefaultBinder.MakeError(((DefaultBinder)binder).MakeNonPublicMemberGetError(resolverFactory, this, type, instance), BindingRestrictions.Empty, typeof(object)); } - public override ErrorInfo GetBoundError(ActionBinder binder, Expression instance) { + public override ErrorInfo GetBoundError(ActionBinder binder, DynamicMetaObject instance) { MethodInfo getter = ResolveGetter(binder.PrivateBinding); if (getter == null) { @@ -139,7 +139,7 @@ public abstract class PropertyTracker : MemberTracker { throw new InvalidOperationException(); } - public override MemberTracker BindToInstance(Expression instance) { + public override MemberTracker BindToInstance(DynamicMetaObject instance) { return new BoundMemberTracker(this, instance); } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/RuleBuilder.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/RuleBuilder.cs deleted file mode 100644 index 27b7c8c793..0000000000 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/RuleBuilder.cs +++ /dev/null @@ -1,291 +0,0 @@ -/* **************************************************************************** - * - * Copyright (c) Microsoft Corporation. - * - * This source code is subject to terms and conditions of the Microsoft Public License. A - * copy of the license can be found in the License.html file at the root of this distribution. If - * you cannot locate the Microsoft Public License, please send an email to - * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound - * by the terms of the Microsoft Public License. - * - * You must not remove this notice, or any other, from this software. - * - * - * ***************************************************************************/ - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq.Expressions; -using System.Reflection; -using System.Dynamic; -using Microsoft.Contracts; -using Microsoft.Scripting.Generation; -using Microsoft.Scripting.Runtime; -using Microsoft.Scripting.Utils; -using AstUtils = Microsoft.Scripting.Ast.Utils; - -namespace Microsoft.Scripting.Actions { - using Ast = System.Linq.Expressions.Expression; - - /// - /// Rule Builder - /// - /// A rule is the mechanism that LanguageBinders use to specify both what code to execute (the Target) - /// for a particular action on a particular set of objects, but also a Test that guards the Target. - /// Whenver the Test returns true, it is assumed that the Target will be the correct action to - /// take on the arguments. - /// - /// In the current design, a RuleBuilder is also used to provide a mini binding scope for the - /// parameters and temporary variables that might be needed by the Test and Target. This will - /// probably change in the future as we unify around the notion of Lambdas. - /// - /// TODO: remove once everyone is converted over to MetaObjects - /// - public sealed class RuleBuilder { - internal Expression _test; // the test that determines if the rule is applicable for its parameters - internal Expression _target; // the target that executes if the rule is true - internal readonly Expression _context; // CodeContext, if any. - private bool _error; // true if the rule represents an error - internal List _temps; // temporaries allocated by the rule - - // the parameters which the rule is processing - internal readonly IList _parameters; - - // the return label of the rule - internal readonly LabelTarget _return; - - /// - /// Completed rule - /// - private Expression _binding; - - public RuleBuilder(ReadOnlyCollection parameters, LabelTarget returnLabel) { - - if (parameters.Count > 0 && typeof(CodeContext).IsAssignableFrom(parameters[0].Type)) { - _context = parameters[0]; - var p = ArrayUtils.RemoveAt(parameters, 0); - _parameters = p; - } else { - // TODO: remove the copy when we have covariant IEnumerable - _parameters = parameters.ToArray(); - } - _return = returnLabel; - } - - public void Clear() { - _test = null; - _target = null; - _error = false; - _temps = null; - } - - /// - /// An expression that should return true if and only if Target should be executed - /// - public Expression Test { - get { return _test; } - set { - ContractUtils.RequiresNotNull(value, "value"); - ContractUtils.Requires(TypeUtils.IsBool(value.Type), "value", Strings.TypeOfTestMustBeBool); - _test = value; - } - } - - /// - /// The code to execute if the Test is true. - /// - public Expression Target { - get { return _target; } - set { _target = value; } - } - - public Expression Context { - get { - return _context; - } - } - - /// - /// Gets the logical parameters to the dynamic site in the form of Expressions. - /// - public IList Parameters { - get { - return _parameters; - } - } - - public LabelTarget ReturnLabel { - get { return _return; } - } - - /// - /// Allocates a temporary variable for use during the rule. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] - public ParameterExpression GetTemporary(Type type, string name) { - ParameterExpression t = Expression.Variable(type, name); - AddTemporary(t); - return t; - } - - public void AddTemporary(ParameterExpression variable) { - ContractUtils.RequiresNotNull(variable, "variable"); - if (_temps == null) { - _temps = new List(); - } - _temps.Add(variable); - } - - public Expression MakeReturn(ActionBinder binder, Expression expr) { - // we create a temporary here so that ConvertExpression doesn't need to (because it has no way to declare locals). - if (expr.Type != typeof(void)) { - ParameterExpression variable = GetTemporary(expr.Type, "$retVal"); - Expression conv = binder.ConvertExpression(variable, ReturnType, ConversionResultKind.ExplicitCast, Context); - if (conv == variable) return MakeReturn(expr); - - return MakeReturn(Ast.Block(Ast.Assign(variable, expr), conv)); - } - return MakeReturn(binder.ConvertExpression(expr, ReturnType, ConversionResultKind.ExplicitCast, Context)); - } - - private Expression MakeReturn(Expression expression) { - return Ast.Return(_return, AstUtils.Convert(expression, _return.Type)); - } - - public Expression MakeError(Expression expr) { - if (expr != null) { - // TODO: Change to ConvertHelper - if (!TypeUtils.CanAssign(typeof(Exception), expr.Type)) { - expr = Ast.Convert(expr, typeof(Exception)); - } - } - - _error = true; - return Ast.Throw(expr); - } - - public bool IsError { - get { - return _error; - } - set { - _error = value; - } - } - - public void AddTest(Expression expression) { - ContractUtils.RequiresNotNull(expression, "expression"); - ContractUtils.Requires(TypeUtils.IsBool(expression.Type), "expression", Strings.TypeOfExpressionMustBeBool); - - if (_test == null) { - _test = expression; - } else { - _test = Ast.AndAlso(_test, expression); - } - } - - public void MakeTest(params Type[] types) { - _test = MakeTestForTypes(types, 0); - } - - public static Expression MakeTypeTestExpression(Type t, Expression expr) { - // we must always check for non-sealed types explicitly - otherwise we end up - // doing fast-path behavior on a subtype which overrides behavior that wasn't - // present for the base type. - //TODO there's a question about nulls here - if (CompilerHelpers.IsSealed(t) && t == expr.Type) { - if (t.IsValueType) { - return AstUtils.Constant(true); - } - return Ast.NotEqual(expr, AstUtils.Constant(null)); - } - - return Ast.AndAlso( - Ast.NotEqual( - expr, - AstUtils.Constant(null)), - Ast.Equal( - Ast.Call( - AstUtils.Convert(expr, typeof(object)), - typeof(object).GetMethod("GetType") - ), - AstUtils.Constant(t) - ) - ); - } - - public Expression MakeTestForTypes(Type[] types, int index) { - Expression test = MakeTypeTest(types[index], index); - if (index < types.Length - 1) { - Expression nextTests = MakeTestForTypes(types, index + 1); - if (ConstantCheck.Check(test, true)) { - return nextTests; - } else if (ConstantCheck.Check(nextTests, true)) { - return test; - } else { - return Ast.AndAlso(test, nextTests); - } - } else { - return test; - } - } - - public Expression MakeTypeTest(Type type, int index) { - return MakeTypeTest(type, Parameters[index]); - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] - public Expression MakeTypeTest(Type type, Expression tested) { - if (type == null || type == typeof(DynamicNull)) { - return Ast.Equal(tested, AstUtils.Constant(null)); - } - - return MakeTypeTestExpression(type, tested); - } - - /// - /// Gets the number of logical parameters the dynamic site is provided with. - /// - public int ParameterCount { - get { - return _parameters.Count; - } - } - - public Expression MakeTypeTestExpression(Type t, int param) { - return MakeTypeTestExpression(t, Parameters[param]); - } - - [Confined] - public override string ToString() { - return string.Format("RuleBuilder({0})", _target); - } - - public Type ReturnType { - get { return _return.Type; } - } - - public Expression CreateRule() { - if (_binding == null) { - if (_test == null) { - throw Error.MissingTest(); - } - if (_target == null) { - throw Error.MissingTarget(); - } - - _binding = Expression.Block( - _temps != null ? _temps.ToArray() : new ParameterExpression[0], - Expression.Condition( - _test, - AstUtils.Convert(_target, typeof(void)), - AstUtils.Empty() - ) - ); - } - - return _binding; - } - } -} diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/TypeGroup.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/TypeGroup.cs index 3c34c660f6..be06a77fb3 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/TypeGroup.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/TypeGroup.cs @@ -83,7 +83,7 @@ public sealed class TypeGroup : TypeTracker { return repr.ToString(); } - public override IList GetMemberNames(CodeContext context) { + public override IList GetMemberNames() { Dictionary members = new Dictionary(); foreach (Type t in this.Types) { CollectMembers(members, t); diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/TypeTracker.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/TypeTracker.cs index 067fc38d34..5ab0445916 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Actions/TypeTracker.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Actions/TypeTracker.cs @@ -38,15 +38,15 @@ public abstract class TypeTracker : MemberTracker, IMembersList { #region IMembersList Members - public virtual IList GetMemberNames(CodeContext context) { + public virtual IList GetMemberNames() { Dictionary members = new Dictionary(); CollectMembers(members, Type); return MembersToList(members); } - internal static IList MembersToList(Dictionary members) { - List res = new List(); + internal static IList MembersToList(Dictionary members) { + List res = new List(); foreach (string key in members.Keys) { res.Add(key); } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Ast/CodeContextExpression.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Ast/CodeContextExpression.cs deleted file mode 100644 index 457aa0f05b..0000000000 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Ast/CodeContextExpression.cs +++ /dev/null @@ -1,109 +0,0 @@ -/* **************************************************************************** - * - * Copyright (c) Microsoft Corporation. - * - * This source code is subject to terms and conditions of the Microsoft Public License. A - * copy of the license can be found in the License.html file at the root of this distribution. If - * you cannot locate the Microsoft Public License, please send an email to - * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound - * by the terms of the Microsoft Public License. - * - * You must not remove this notice, or any other, from this software. - * - * - * ***************************************************************************/ - -using System; -using System.Linq.Expressions; -using Microsoft.Scripting.Runtime; -using Microsoft.Scripting.Utils; - -namespace Microsoft.Scripting.Ast { - - /// - /// Evaluates to the CodeContext that's currently in scope - /// - /// TODO: this should go away as an intrinsic in favor of languages - /// tracking their own scope chain explicitly - /// - public sealed class CodeContextExpression : Expression { - internal static readonly CodeContextExpression Instance = new CodeContextExpression(); - - internal CodeContextExpression() { - } - - public sealed override Type Type { - get { return typeof(CodeContext); } - } - - public sealed override ExpressionType NodeType { - get { return ExpressionType.Extension; } - } - - protected override Expression VisitChildren(ExpressionVisitor visitor) { - return this; - } - } - - /// - /// Creates a new scope where the specified CodeContext will be valid - /// - /// TODO: this should go away as an intrinsic in favor of languages - /// tracking their own scope chain explicitly - /// - public sealed class CodeContextScopeExpression : Expression { - private readonly Expression _newContext; - private readonly Expression _body; - - internal CodeContextScopeExpression(Expression body, Expression newContext) { - _body = body; - _newContext = newContext; - } - - public sealed override Type Type { - get { return _body.Type; } - } - - public sealed override ExpressionType NodeType { - get { return ExpressionType.Extension; } - } - - /// - /// The body where the new CodeContext can be used - /// - public Expression Body { - get { return _body; } - } - - /// - /// The expression that initializes the new CodeContext for this scope - /// - public Expression NewContext { - get { return _newContext; } - } - - protected override Expression VisitChildren(ExpressionVisitor visitor) { - Expression newContext = visitor.Visit(_newContext); - Expression body = visitor.Visit(_body); - - if (newContext == _newContext && body == _body) { - return this; - } - - return Utils.CodeContextScope(body, newContext); - } - } - - public partial class Utils { - public static Expression CodeContext() { - return CodeContextExpression.Instance; - } - public static CodeContextScopeExpression CodeContextScope(Expression body, Expression newContext) { - ContractUtils.RequiresNotNull(body, "body"); - ContractUtils.RequiresNotNull(newContext, "newContext"); - ContractUtils.Requires(TypeUtils.AreAssignable(typeof(CodeContext), newContext.Type), "newContext"); - - return new CodeContextScopeExpression(body, newContext); - } - } -} diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Ast/LambdaBuilder.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Ast/LambdaBuilder.cs index 61aa9510b5..eb555b2e53 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Ast/LambdaBuilder.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Ast/LambdaBuilder.cs @@ -47,7 +47,6 @@ public class LambdaBuilder { private Expression _body; private bool _dictionary; private bool _visible = true; - private bool _addCodeContext; private bool _completed; private static int _lambdaId; //for generating unique lambda name @@ -148,20 +147,7 @@ public class LambdaBuilder { _visible = value; } } - - /// - /// Prevents builder from inserting context scope. - /// Default is false (will insert if needed). - /// - public bool AddCodeContext { - get { - return _addCodeContext; - } - set { - _addCodeContext = value; - } - } - + public List GetVisibleVariables() { var vars = new List(_visibleVars.Count); foreach (var v in _visibleVars) { @@ -538,25 +524,7 @@ public class LambdaBuilder { private Expression MakeBody() { Expression body = _body; - - // wrap a CodeContext scope if needed - if (AddCodeContext) { - - var vars = GetVisibleVariables(); - - if (vars.Count > 0) { - body = Utils.CodeContextScope( - body, - Expression.Call( - typeof(RuntimeHelpers).GetMethod("CreateNestedCodeContext"), - Utils.VariableDictionary(vars), - Utils.CodeContext(), - AstUtils.Constant(_visible) - ) - ); - } - } - + // wrap a scope if needed if (_locals != null && _locals.Count > 0) { body = Expression.Block(new ReadOnlyCollection(_locals.ToArray()), body); @@ -611,11 +579,6 @@ public static partial class Utils { namespace Microsoft.Scripting.Runtime { public static partial class ScriptingRuntimeHelpers { - public static CodeContext CreateNestedCodeContext(CustomSymbolDictionary variables, CodeContext context, bool visible) { - Debug.Assert(variables.Count > 0); - return new CodeContext(new Scope(context.Scope, variables, visible), context.LanguageContext, context); - } - /// /// Used by prologue code that is injected in lambdas to ensure that delegate signature matches what /// lambda body expects. Such code typically unwraps subset of the params array manually, diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Generation/CompilerHelpers.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Generation/CompilerHelpers.cs index 60e8e818e8..c2383a1237 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Generation/CompilerHelpers.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Generation/CompilerHelpers.cs @@ -662,15 +662,6 @@ public static class CompilerHelpers { return res; } - /// - /// Returns a value which indicates failure when a ConvertToAction of ImplicitTry or - /// ExplicitTry. - /// - public static Expression GetTryConvertReturnValue(CodeContext context, RuleBuilder rule) { - rule.IsError = true; - return rule.MakeReturn(context.LanguageContext.Binder, GetTryConvertReturnValue(rule.ReturnType)); - } - public static bool HasTypeConverter(Type fromType, Type toType) { #if SILVERLIGHT return false; diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Microsoft.Scripting.Build.csproj b/Merlin/Main/Runtime/Microsoft.Scripting/Microsoft.Scripting.Build.csproj index ea011f604e6fad61092a99400491cbf26d41330f..8bc99e6f7e8c19ab178ec7ba65811d7d46613821 100644 GIT binary patch delta 24 gcmey?%DkzWc|(HH<`YKeL^gAI{Bzx0(AQ=H0FM|8I{*Lx delta 64 zcmdng%>1pDc|(E`YY;;zL(b$to8-+2M(0EXQy5YioEh>N@)$~htO|yb$sglHCqMA< T+N|ZySIGNED true 857735168 - ..\..\Utilities\Silverlight\x86ret\ + ..\..\Utilities\Silverlight\x86ret\ pdbonly @@ -85,8 +85,8 @@ true - - + + False $(SilverlightPath)\mscorlib.dll @@ -96,8 +96,8 @@ $(SilverlightPath)\System.dll - - + + @@ -144,7 +144,6 @@ - @@ -353,7 +352,6 @@ - @@ -369,7 +367,6 @@ - diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/BinderOps.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/BinderOps.cs index 802df04c2b..9e031bfa04 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/BinderOps.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/BinderOps.cs @@ -92,45 +92,7 @@ public static class BinderOps { } return res; } - - #region Event support - - public static EventTracker EventTrackerInPlaceAdd(CodeContext context, EventTracker self, T target) { - MethodInfo add = self.Event.GetAddMethod(context.LanguageContext.DomainManager.Configuration.PrivateBinding); - add.Invoke(null, new object[] { target }); - return self; - } - - public static EventTracker EventTrackerInPlaceRemove(CodeContext context, EventTracker self, T target) { - MethodInfo remove = self.Event.GetRemoveMethod(context.LanguageContext.DomainManager.Configuration.PrivateBinding); - remove.Invoke(null, new object[] { target }); - return self; - } - - public static BoundMemberTracker BoundEventTrackerInPlaceAdd(CodeContext context, BoundMemberTracker self, T target) { - if (self.BoundTo.MemberType == TrackerTypes.Event) { - EventTracker et = (EventTracker)self.BoundTo; - - MethodInfo add = et.Event.GetAddMethod(context.LanguageContext.DomainManager.Configuration.PrivateBinding); - add.Invoke(self.ObjectInstance, new object[] { target }); - return self; - } - throw new InvalidOperationException(); - } - - public static BoundMemberTracker BoundEventTrackerInPlaceRemove(CodeContext context, BoundMemberTracker self, T target) { - if (self.BoundTo.MemberType == TrackerTypes.Event) { - EventTracker et = (EventTracker)self.BoundTo; - - MethodInfo remove = et.Event.GetRemoveMethod(context.LanguageContext.DomainManager.Configuration.PrivateBinding); - remove.Invoke(self.ObjectInstance, new object[] { target }); - return self; - } - throw new InvalidOperationException(); - } - #endregion - public static ArgumentTypeException BadArgumentsForOperation(Operators op, params object[] args) { StringBuilder message = new StringBuilder("unsupported operand type(s) for operation "); message.Append(op.ToString()); diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/DefaultLanguageContext.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/DefaultLanguageContext.cs index 299fee4c54..4710f3358a 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/DefaultLanguageContext.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/DefaultLanguageContext.cs @@ -48,7 +48,7 @@ public DefaultActionBinder(ScriptDomainManager manager, Type[] extensionTypes) throw new NotImplementedException(); } - public override Expression ConvertExpression(Expression expr, Type toType, ConversionResultKind kind, Expression context) { + public override Expression ConvertExpression(Expression expr, Type toType, ConversionResultKind kind, OverloadResolverFactory factory) { if (toType.IsAssignableFrom(expr.Type)) { return expr; } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/DynamicStackFrame.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/DynamicStackFrame.cs index fa0507a48a..56fc942778 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/DynamicStackFrame.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/DynamicStackFrame.cs @@ -20,26 +20,18 @@ namespace Microsoft.Scripting.Runtime { /// Helper for storing information about stack frames. /// public class DynamicStackFrame { - private CodeContext _context; private string _funcName; private string _filename; private int _lineNo; private MethodBase _method; - public DynamicStackFrame(CodeContext context, MethodBase method, string funcName, string filename, int line) { - _context = context; + public DynamicStackFrame(MethodBase method, string funcName, string filename, int line) { _funcName = funcName; _filename = filename; _lineNo = line; _method = method; } - public CodeContext CodeContext { - get { - return _context; - } - } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public MethodBase GetMethod() { return _method; diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/ExceptionHelpers.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/ExceptionHelpers.cs index 7196e66179..afe1bd01bd 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/ExceptionHelpers.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/ExceptionHelpers.cs @@ -112,17 +112,7 @@ public static class ExceptionHelpers { return TryGetAssociatedStackTraces(rethrow, out result) ? result : null; } - public static void UpdateStackTrace(CodeContext context, MethodBase method, string funcName, string filename, int line) { - if (line != -1) { - Debug.Assert(filename != null); - if (_stackFrames == null) _stackFrames = new List(); - - Debug.Assert(line != SourceLocation.None.Line); - - _stackFrames.Add(new DynamicStackFrame(context, method, funcName, filename, line)); - } - } - + public static List AssociateDynamicStackFrames(Exception clrException) { if (_stackFrames != null) { clrException.Data[typeof(DynamicStackFrame)] = _stackFrames; @@ -287,7 +277,7 @@ public static class ExceptionHelpers { } } - return new DynamicStackFrame(null, method, methodName, filename, line); + return new DynamicStackFrame(method, methodName, filename, line); } #endregion diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/IMembersList.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/IMembersList.cs index c3807140e8..0d5cd6b25a 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/IMembersList.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Runtime/IMembersList.cs @@ -18,13 +18,9 @@ namespace Microsoft.Scripting.Runtime { /// - /// Provides a list of all the members of an instance. ie. all the keys in the - /// dictionary of the object. Note that it can contain objects that are not strings. - /// - /// Such keys can be added in IronPython using syntax like: - /// obj.__dict__[100] = someOtherObject + /// Provides a list of all the members of an instance. /// public interface IMembersList { - IList GetMemberNames(CodeContext context); + IList GetMemberNames(); } } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Utils/ReadOnlyDictionary.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Utils/ReadOnlyDictionary.cs index b522efa81f..6817cbf681 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Utils/ReadOnlyDictionary.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Utils/ReadOnlyDictionary.cs @@ -20,7 +20,7 @@ namespace Microsoft.Scripting.Utils { // Like ReadOnlyCollection: wraps an IDictionary in a read-only wrapper [Serializable] - internal sealed class ReadOnlyDictionary : IDictionary { + public sealed class ReadOnlyDictionary : IDictionary { // For wrapping non-readonly Keys, Values collections // Not used for standard dictionaries, which return read-only Keys and Values @@ -84,7 +84,7 @@ private sealed class ReadOnlyWrapper : ICollection { private readonly IDictionary _dict; - internal ReadOnlyDictionary(IDictionary dict) { + public ReadOnlyDictionary(IDictionary dict) { ReadOnlyDictionary rodict = dict as ReadOnlyDictionary; _dict = (rodict != null) ? rodict._dict : dict; } diff --git a/Merlin/Main/Runtime/Microsoft.Scripting/Utils/SynchronizedDictionary.cs b/Merlin/Main/Runtime/Microsoft.Scripting/Utils/SynchronizedDictionary.cs index 70e9e04658..c4be39c5e3 100644 --- a/Merlin/Main/Runtime/Microsoft.Scripting/Utils/SynchronizedDictionary.cs +++ b/Merlin/Main/Runtime/Microsoft.Scripting/Utils/SynchronizedDictionary.cs @@ -23,22 +23,28 @@ namespace Microsoft.Scripting.Utils { /// provides a thread-safe implementation. It holds onto a Dictionary[TKey, TValue] instead of inheriting from /// it so that users who need to do manual synchronization can access the underlying Dictionary[TKey, TValue]. /// - internal class SynchronizedDictionary : + public class SynchronizedDictionary : IDictionary, ICollection>, IEnumerable> { - Dictionary _dictionary = new Dictionary(); + Dictionary _dictionary; /// /// This returns the raw unsynchronized Dictionary[TKey, TValue]. Users are responsible for locking /// on it before accessing it. Also, it should not be arbitrarily handed out to other code since deadlocks /// can be caused if other code incorrectly locks on it. /// - internal Dictionary UnderlyingDictionary { - get { - return _dictionary; - } + public Dictionary UnderlyingDictionary { + get { return _dictionary; } + } + + public SynchronizedDictionary() + : this(new Dictionary()) { + } + + public SynchronizedDictionary(Dictionary dictionary) { + _dictionary = dictionary; } #region IDictionary Members diff --git a/ndp/fx/src/Core/Microsoft/Scripting/Microsoft.Scripting.Core.csproj b/ndp/fx/src/Core/Microsoft/Scripting/Microsoft.Scripting.Core.csproj index e48b8978c4..478fbebce7 100644 --- a/ndp/fx/src/Core/Microsoft/Scripting/Microsoft.Scripting.Core.csproj +++ b/ndp/fx/src/Core/Microsoft/Scripting/Microsoft.Scripting.Core.csproj @@ -21,7 +21,7 @@ true SIGNED true - ..\..\..\..\..\..\Merlin\Main\Utilities\Silverlight\x86ret\ + ..\..\..\..\..\..\Merlin\Main\Utilities\Silverlight\x86ret\ 855638016 @@ -91,8 +91,8 @@ true - - + + False $(SilverlightPath)\mscorlib.dll @@ -101,8 +101,8 @@ False $(SilverlightPath)\System.dll - - + + diff --git a/ndp/fx/src/Core/Microsoft/Scripting/Microsoft.Scripting.ExtensionAttribute.csproj b/ndp/fx/src/Core/Microsoft/Scripting/Microsoft.Scripting.ExtensionAttribute.csproj index dc9c1c18f2..0b4aac36ed 100644 --- a/ndp/fx/src/Core/Microsoft/Scripting/Microsoft.Scripting.ExtensionAttribute.csproj +++ b/ndp/fx/src/Core/Microsoft/Scripting/Microsoft.Scripting.ExtensionAttribute.csproj @@ -19,7 +19,7 @@ SIGNED true 866123776 - ..\..\..\..\..\..\Merlin\Main\Utilities\Silverlight\x86ret\ + ..\..\..\..\..\..\Merlin\Main\Utilities\Silverlight\x86ret\ pdbonly @@ -79,7 +79,7 @@ true - + False $(SilverlightPath)\mscorlib.dll