public void UpdateForReload(PythonModule reloaded) { this.__dict__ = reloaded.__dict__; this.initialize = reloaded.initialize; Initialize(); }
public override Dict GetAttrDict(ICallerContext context, object self) { // Get the entries from the type Dict res = new Dict(GetAttrDict(context)); // Add the entries from the instance ISuperDynamicObject sdo = self as ISuperDynamicObject; if (sdo != null) { IAttributesDictionary dict = sdo.GetDict(); if (dict != null) { foreach (KeyValuePair <object, object> val in dict) { object fieldName = val.Key; if (!res.ContainsKey(fieldName)) { res.Add(new KeyValuePair <object, object>(fieldName, val.Value)); } } } } return(res); }
public PythonModule(string name, IDictionary <object, object> dict, SystemState state, InitializeModule init, CallerContextFlags callerContextFlags) { Debug.Assert(state != null); if (dict is IAttributesDictionary) { __dict__ = (IAttributesDictionary)dict; } else { __dict__ = new FieldIdDict(dict); } ModuleName = name; __dict__[SymbolTable.Builtins] = TypeCache.Builtin; if (name == "__main__") { Debug.WriteLine("==========__main__"); } initialize = init; contextFlags = callerContextFlags; systemState = state; }
public void SetAttr(ICallerContext context, SymbolId name, object value) { switch (name.Id) { case SymbolTable.BasesId: __bases__ = ValidateBases(value); break; case SymbolTable.NameId: string n = value as string; if (n == null) { throw Ops.TypeError("TypeError: __name__ must be a string object"); } __name__ = n; break; case SymbolTable.DictId: IAttributesDictionary d = value as IAttributesDictionary; if (d == null) { throw Ops.TypeError("__dict__ must be set to dictionary"); } __dict__ = d; break; case SymbolTable.UnassignId: hasFinalizer = true; goto default; default: __dict__[name] = value; break; } }
internal ModuleScope(PythonModule mod, IAttributesDictionary globals, object locals) { __module__ = mod; f_globals = globals; f_locals = locals; __builtin__ = TypeCache.Builtin; }
private IAttributesDictionary EnsureDict() { if (dict == null) { dict = new FieldIdDict(); } return(dict); }
/// <summary> /// Performs sys's initialization /// It is in it's own function so we can do reload(sys). On reload(sys), most of the attributes need to be /// reset. The following are left as they are - argv, exc_type, modules, path, path_hooks, path_importer_cache, ps1, ps2. /// </summary> public void Initialize() { if (__dict__ == null) { __dict__ = new FieldIdDict(); // These fields do not get reset on "reload(sys)" argv = Ops.MakeList(); modules = new Dict(); path = List.Make(); ps1 = Ops.ToPython(">>> "); ps2 = Ops.ToPython("... "); __stdin__ = new PythonFile(Console.OpenStandardInput(), Console.InputEncoding, "<stdin>", "r"); __stdout__ = new PythonFile(Options.UnbufferedStdOutAndError ? Console.OpenStandardOutput(0) : Console.OpenStandardOutput(), Console.OutputEncoding, "<stdout>", "w"); __stderr__ = new PythonFile(Options.UnbufferedStdOutAndError ? Console.OpenStandardError(0) : Console.OpenStandardError(), Console.OutputEncoding, "<stderr>", "w"); } __dict__[SymbolTable.Name] = "sys"; stdin = __stdin__; stdout = __stdout__; stderr = __stderr__; // removed from dictionary after the first call to set it. MethodInfo mi = typeof(SystemState).GetMethod("setdefaultencodingImpl", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); BuiltinMethodDescriptor descr = (BuiltinMethodDescriptor) new ReflectedMethod("setdefaultencoding", mi, FunctionType.PythonVisible | FunctionType.Method).GetDescriptor(); __dict__[SymbolTable.SetDefaultEncoding] = descr.GetAttribute(this, this); DefaultEncoding = Encoding.ASCII; byteorder = BitConverter.IsLittleEndian ? "little" : "big"; copyright = "Copyright (c) Microsoft Corporation. All rights reserved."; hexversion = 0x02040000; maxint = Int32.MaxValue; maxunicode = (int)ushort.MaxValue; platform = Ops.ToPython("cli"); version_info = Tuple.MakeTuple(2, 4); // !!! These fields do need to be reset on "reload(sys)". However, the initial value is specified by the // engine elsewhere. For now, we initialize them just once to some default value if (version == null) { version = IronPython.Hosting.PythonEngine.VersionString; warnoptions = List.Make(); executable = ""; } }
public static void SetWeakRefHelper(object self, WeakRefTracker value) { ISuperDynamicObject sdo = self as ISuperDynamicObject; System.Diagnostics.Debug.Assert(sdo != null); IAttributesDictionary d = GetInitializedDict(sdo); d[SymbolTable.WeakRef] = value; }
private WeakRefTracker weakRef; // initialized if user defines finalizer on class or instance public OldInstance(OldClass _class) { __class__ = _class; __dict__ = new CustomOldClassDict(); if (__class__.HasFinalizer) { // class defines finalizer, we get it automatically. AddFinalizer(); } }
private static IAttributesDictionary GetInitializedDict(ISuperDynamicObject self) { IAttributesDictionary d = self.GetDict(); if (d == null) { d = new FieldIdDict(); self.SetDict(d); } return(d); }
internal EngineModule(string moduleName, IDictionary<string, object> globalsDict, SystemState systemState) { Debug.Assert(moduleName != null); globals = globalsDict; if (globals is IAttributesDictionary) globalsAdapter = globals as IAttributesDictionary; else globalsAdapter = new StringDictionaryAdapterDict(globalsDict); PythonModule pythonModule = new PythonModule(moduleName, globalsAdapter, systemState); defaultModuleScope = new ModuleScope(pythonModule); }
public void SetAttr(ICallerContext context, SymbolId name, object value) { if (name.Id == SymbolTable.ClassId) { OldClass oc = value as OldClass; if (oc == null) { throw Ops.TypeError("__class__ must be set to class"); } __class__ = oc; } else if (name.Id == SymbolTable.DictId) { IAttributesDictionary dict = value as IAttributesDictionary; if (dict == null) { throw Ops.TypeError("__dict__ must be set to a dictionary"); } if (HasFinalizer() && !__class__.HasFinalizer) { if (!dict.ContainsKey(SymbolTable.Unassign)) { ClearFinalizer(); } } else if (dict.ContainsKey(SymbolTable.Unassign)) { AddFinalizer(); } __dict__ = dict; } else if (name.Id == SymbolTable.UnassignId) { if (!HasFinalizer()) { // user is defining __del__ late bound for the 1st time AddFinalizer(); } __dict__[name] = value; } else { __dict__[name] = value; } }
public void SetAttr(ICallerContext context, SymbolId name, object value) { if (name == SymbolTable.Dict) { // our Python Dictionaries implement this explicitly IAttributesDictionary d = value as IAttributesDictionary; if (d == null) { throw Ops.TypeError("__dict__ must be set to dictionary"); } dict = d; } else { EnsureDict()[name] = value; } }
public static WeakRefTracker GetWeakRefHelper(object self) { ISuperDynamicObject sdo = self as ISuperDynamicObject; if (sdo != null) { IAttributesDictionary dict = sdo.GetDict(); if (dict != null) { object res; if (dict.TryGetValue(SymbolTable.WeakRef, out res)) { return(res as WeakRefTracker); } } } return(null); }
public void BaseDelAttr(ICallerContext context, ISuperDynamicObject self, SymbolId name) { object slot; if (!TryLookupSlot(context, name, out slot)) { IAttributesDictionary d = GetInitializedDict((ISuperDynamicObject)self); //!!! forces dict init if (d.ContainsKey(name)) { d.Remove(name); return; } else { throw Ops.AttributeError("no slot named {0} on {1}", SymbolTable.IdToString(name), this.__name__); } } Ops.DelDescriptor(slot, self); }
public OldClass(string name, Tuple bases, IDictionary <object, object> dict) { __bases__ = bases; //!!! validate, maybe even sort __name__ = name; __dict__ = (IAttributesDictionary)dict; if (!__dict__.ContainsKey(SymbolTable.Doc)) { __dict__[SymbolTable.Doc] = null; } if (__dict__.ContainsKey(SymbolTable.Unassign)) { hasFinalizer = true; } PromoteFunctionsToMethods(); }
//!!! private would be better, only called from PythonType internal bool TryBaseGetAttr(ICallerContext context, ISuperDynamicObject self, SymbolId name, out object ret) { if (name == SymbolTable.Dict) { ret = GetInitializedDict(self); return(true); } IAttributesDictionary d = self.GetDict(); if (d != null) { if (d.TryGetValue(name, out ret)) { return(true); } } if (TryLookupSlot(context, name, out ret)) { ret = Ops.GetDescriptor(ret, self, this); return(true); } if (name == SymbolTable.Class) { ret = this; return(true); } if (name == SymbolTable.WeakRef) { ret = null; return(true); } if (!__getattr__F.IsObjectMethod()) { ret = __getattr__F.Invoke(self, SymbolTable.IdToString(name)); return(true); } ret = null; return(false); }
//!!! private would be better, only called from PythonType internal void BaseSetAttr(ICallerContext context, ISuperDynamicObject self, SymbolId name, object value) { object slot; if (TryLookupSlot(context, name, out slot)) { if (Ops.SetDescriptor(slot, self, value)) { return; } } if (name == SymbolTable.WeakRef) { throw Ops.TypeError("attribute '__weakref__' of '{0}' objects is not writable", __name__); } IAttributesDictionary d = GetInitializedDict(self); d[name] = value; }
public override List GetAttrNames(ICallerContext context, object self) { List baseNames = base.GetAttrNames(context, self); ISuperDynamicObject sdo = self as ISuperDynamicObject; if (sdo != null) { IAttributesDictionary dict = sdo.GetDict(); if (dict != null) { foreach (object o in dict.Keys) { if (!baseNames.Contains(o)) { baseNames.Add(o); } } } } return(baseNames); }
protected UserType(string name, Tuple bases, IDictionary <object, object> dict) : base(NewTypeMaker.GetNewType(name, bases, dict)) { List <MethodInfo> ctors = new List <MethodInfo>(); foreach (MethodInfo mi in type.GetMethods()) { if (mi.Name == ReflectedType.MakeNewName) { ctors.Add(mi); } } if (ctors.Count == 0) { throw new NotImplementedException("no MakeNew found"); } ctor = BuiltinFunction.Make(name, ctors.ToArray(), ctors.ToArray(), FunctionType.Function); IAttributesDictionary fastDict = (IAttributesDictionary)dict; this.__name__ = name; this.__module__ = fastDict[SymbolTable.Module]; // should always be present... if (!fastDict.ContainsKey(SymbolTable.Doc)) { fastDict[SymbolTable.Doc] = null; } InitializeUserType(bases, false); this.dict = CreateNamespaceDictionary(dict); AddProtocolWrappers(); }
internal IDictionary<object, object> GetAttrDictWithCustomDict(ICallerContext context, ICustomAttributes self, IAttributesDictionary selfDict) { Debug.Assert(IsInstanceOfType(self)); // Get the attributes from the instance Dict res = new Dict(selfDict); // Add the attributes from the type Dict typeDict = base.GetAttrDict(context, self); foreach (KeyValuePair<object, object> pair in (IDictionary<object, object>)typeDict) { res.Add(pair); } return res; }
/// <summary> /// Types implementing ICustomAttributes need special handling for attribute access since they have their own dictionary /// </summary> internal void SetAttrWithCustomDict(ICallerContext context, ICustomAttributes self, IAttributesDictionary selfDict, SymbolId name, object value) { Debug.Assert(IsInstanceOfType(self)); if (name == SymbolTable.Dict) throw Ops.AttributeErrorForReadonlyAttribute(__name__.ToString(), name); object dummy; if (TryLookupSlot(context, name, out dummy)) { SetAttr(context, self, name, value); } else { selfDict[name] = value; } }
public void SetAttr(ICallerContext context, SymbolId name, object value) { switch (name.Id) { case SymbolTable.BasesId: __bases__ = ValidateBases(value); break; case SymbolTable.NameId: string n = value as string; if (n == null) throw Ops.TypeError("TypeError: __name__ must be a string object"); __name__ = n; break; case SymbolTable.DictId: IAttributesDictionary d = value as IAttributesDictionary; if (d == null) throw Ops.TypeError("__dict__ must be set to dictionary"); __dict__ = d; break; case SymbolTable.UnassignId: HasFinalizer = true; goto default; case SymbolTable.SetAttrId: HasSetAttr = true; goto default; default: __dict__[name] = value; break; } }
internal bool DeleteAttrWithCustomDict(ICallerContext context, ICustomAttributes self, IAttributesDictionary selfDict, SymbolId name) { Debug.Assert(IsInstanceOfType(self)); if (name == SymbolTable.Dict) throw Ops.AttributeErrorForReadonlyAttribute(__name__.ToString(), name); object value; if (selfDict.TryGetValue(name, out value)) { if (value == Uninitialized.instance) return false; selfDict.Remove(name); return true; } object dummy; if (TryLookupSlot(context, name, out dummy)) { selfDict[name] = Uninitialized.instance; return true; } else { return selfDict.Remove(name); } }
private ReflectedPackage() { __dict__ = new FieldIdDict(); loadLevels = new Dictionary<SymbolId, int>(); }
void ISuperDynamicObject.SetDict(IAttributesDictionary dict) { (GetObject() as ISuperDynamicObject).SetDict(dict); }
internal ModuleScope(PythonModule mod, IAttributesDictionary globals, object locals, ICallerContext context) : this(mod, globals, locals) { this.TrueDivision = context.TrueDivision; }
private IAttributesDictionary EnsureDict() { if (dict == null) { dict = new FieldIdDict(); } return dict; }
/// <summary> /// Set up the type /// </summary> /// <param name="resetType">Is an existing type being reset?</param> void InitializeUserType(Tuple newBases, IAttributesDictionary newDict, bool resetType) { newBases = EnsureBaseType(newBases); for (int i = 0; i < newBases.Count; i++) { for (int j = 0; j < newBases.Count; j++) { if (i != j && newBases[i] == newBases[j]) { throw Ops.TypeError("duplicate base class {0}", ((IPythonType)newBases[i]).Name); } } } if (resetType) { // Ensure that we are not switching the CLI type Type newType = NewTypeMaker.GetNewType(__name__.ToString(), newBases, (IDictionary<object, object>)dict); if (type != newType) throw Ops.TypeErrorForIncompatibleObjectLayout("__bases__ assignment", this, newType); foreach (object baseTypeObj in BaseClasses) { if (baseTypeObj is OldClass) continue; DynamicType baseType = baseTypeObj as DynamicType; baseType.RemoveSubclass(this); } } this.bases = newBases; // if our dict, or any of our children, have a finalizer, then // we have a finalizer. bool hasFinalizer = newDict.ContainsKey(SymbolTable.Unassign); foreach (object baseTypeObj in BaseClasses) { if (baseTypeObj is OldClass) continue; DynamicType baseType = baseTypeObj as DynamicType; baseType.AddSubclass(this); UserType ut = baseType as UserType; if (ut != null && ut.HasFinalizer) { hasFinalizer = true; } } HasFinalizer = hasFinalizer; if (!resetType) Initialize(); }
internal EngineModule(ModuleScope scope) { defaultModuleScope = scope; globalsAdapter = scope.Globals; globals = new AttributesDictionaryAdapter(globalsAdapter); }
internal PythonModule(string name, IAttributesDictionary dict, SystemState state) : this(name, dict, state, null, CallerContextAttributes.None) { }
internal PythonModule(string name, IAttributesDictionary dict, SystemState state, InitializeModule init, CallerContextAttributes callerContextFlags) { Debug.Assert(state != null); __dict__ = dict; ModuleName = name; __dict__[SymbolTable.Builtins] = TypeCache.Builtin; initialize = init; contextFlags = callerContextFlags; systemState = state; }
/// <summary> /// Performs sys's initialization /// It is in it's own function so we can do reload(sys). On reload(sys), most of the attributes need to be /// reset. The following are left as they are - argv, exc_type, modules, path, path_hooks, path_importer_cache, ps1, ps2. /// </summary> internal void Initialize() { if (__dict__ == null) { __dict__ = new FieldIdDict(); // These fields do not get reset on "reload(sys)" argv = Ops.MakeList(); modules = new Dict(); modules["sys"] = this; modules["__builtin__"] = Importer.MakePythonModule(this, "__builtin__", TypeCache.Builtin); path = List.Make(); ps1 = ">>> "; ps2 = "... "; isSocketRefCountHookInstalled = false; __stdin__ = new PythonFile(Console.OpenStandardInput(), Console.InputEncoding, "<stdin>", "r"); __stdout__ = new PythonFile(Options.BufferedStandardOutAndError ? Console.OpenStandardOutput() : Console.OpenStandardOutput(0), Console.OutputEncoding, "<stdout>", "w"); __stderr__ = new PythonFile(Options.BufferedStandardOutAndError ? Console.OpenStandardError() : Console.OpenStandardError(0), Console.OutputEncoding, "<stderr>", "w"); } __dict__[SymbolTable.Name] = "sys"; stdin = __stdin__; stdout = __stdout__; stderr = __stderr__; // removed from dictionary after the first call to set it. MethodInfo mi = typeof(SystemState).GetMethod("setdefaultencodingImpl", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); BuiltinMethodDescriptor descr = (BuiltinMethodDescriptor)BuiltinFunction.MakeMethod( "setdefaultencoding", mi, FunctionType.PythonVisible | FunctionType.Method).GetDescriptor(); __dict__[SymbolTable.SetDefaultEncoding] = descr.GetAttribute(this, this); DefaultEncoding = Encoding.ASCII; byteorder = BitConverter.IsLittleEndian ? "little" : "big"; copyright = "Copyright (c) Microsoft Corporation. All rights reserved."; maxint = Int32.MaxValue; maxunicode = (int)ushort.MaxValue; platform = "cli"; version_info = Tuple.MakeTuple(2, 4, 0, "final", 0); // report as being compatible w/ 2.4.0 final winver = "2.4"; // !!! These fields do need to be reset on "reload(sys)". However, the initial value is specified by the // engine elsewhere. For now, we initialize them just once to some default value if (version == null) { SetVersion(PythonEngine.VersionString); warnoptions = List.Make(); executable = ""; } }
bool ISuperDynamicObject.SetDict(IAttributesDictionary dict) { return (GetObject() as ISuperDynamicObject).SetDict(dict); }
protected ReflectedPackage() { __dict__ = new FieldIdDict(); loadLevels = new Dictionary <SymbolId, int>(); }
private void PopulateDefaultDictionary(IAttributesDictionary fastDict) { if (!fastDict.ContainsKey(SymbolTable.Doc)) { fastDict[SymbolTable.Doc] = null; } if (HasWeakRef && !fastDict.ContainsKey(SymbolTable.WeakRef)) { fastDict[SymbolTable.WeakRef] = new WeakRefWrapper(this); } if (!fastDict.ContainsKey(SymbolTable.Dict)) { fastDict[SymbolTable.Dict] = new DictWrapper(this); } }
private int attrs; // actually OldClassAttributes - losing type safety for thread safety #endregion Fields #region Constructors public OldClass(string name, Tuple bases, IDictionary<object, object> dict) { __bases__ = bases; //!!! validate, maybe even sort __name__ = name; __dict__ = (IAttributesDictionary)dict; if (!__dict__.ContainsKey(SymbolTable.Doc)) { __dict__[SymbolTable.Doc] = null; } if (__dict__.ContainsKey(SymbolTable.Unassign)) { HasFinalizer = true; } if (__dict__.ContainsKey(SymbolTable.SetAttr)) { HasSetAttr = true; } }
/// <summary> /// called from generated code for overridden methods /// </summary> public bool TryGetNonInheritedMethodHelper(object instance, IAttributesDictionary instanceDict, SymbolId name, int key, out object value) { if (instanceDict != null) { if (instanceDict.TryGetValue(name, out value)) return true; } if (((NamespaceDictionary)dict).TryGetNonInheritedValue(key, out value)) { value = Ops.GetDescriptor(value, instance, this); return true; } return false; }
public void SetAttr(ICallerContext context, SymbolId name, object value) { object setFunc; if (name.Id == SymbolTable.ClassId) { OldClass oc = value as OldClass; if (oc == null) { throw Ops.TypeError("__class__ must be set to class"); } __class__ = oc; } else if (name.Id == SymbolTable.DictId) { IAttributesDictionary dict = value as IAttributesDictionary; if (dict == null) { throw Ops.TypeError("__dict__ must be set to a dictionary"); } if (HasFinalizer() && !__class__.HasFinalizer) { if (!dict.ContainsKey(SymbolTable.Unassign)) { ClearFinalizer(); } } else if (dict.ContainsKey(SymbolTable.Unassign)) { AddFinalizer(); } __dict__ = dict; } else if (__class__.HasSetAttr && __class__.TryLookupSlot(SymbolTable.SetAttr, out setFunc)) { Ops.Call(Ops.GetDescriptor(setFunc, this, __class__), name.ToString(), value); } else if (name.Id == SymbolTable.UnassignId) { if (!HasFinalizer()) { // user is defining __del__ late bound for the 1st time AddFinalizer(); } __dict__[name] = value; } else { __dict__[name] = value; } }
public OldInstance(OldClass _class) { __class__ = _class; __dict__ = new CustomOldClassDict(); if (__class__.HasFinalizer) { // class defines finalizer, we get it automatically. AddFinalizer(); } }
public void SetAttr(ICallerContext context, SymbolId name, object value) { if (name == SymbolTable.Dict) { // our Python Dictionaries implement this explicitly IAttributesDictionary d = value as IAttributesDictionary; if (d == null) { throw Ops.TypeError("__dict__ must be set to dictionary"); } dict = d; } else if(name == SymbolTable.Name || name == SymbolTable.FunctionName) { this.name = Converter.ConvertToString(value); } else { EnsureDict()[name] = value; } }
public void SetDict(IAttributesDictionary dict) { __dict__ = dict; }