public TotemScopeExtension(TotemContext context, Scope scope) : base(scope) { _codeContext = new CodeContext(new TotemDictionary( new ScopeDictionaryStorage(context, scope) ), null, context); }
public static Expression Resolve(this Expression source, IGeneratedQueryCode gc, ICodeContext cc, CompositionContainer container) { if (cc == null) { cc = new CodeContext(); } // It does happen that we are asked to translate a null expression. This could be a static method call, for example. if (source == null) return null; try { Debug.WriteLine("Expression Resolver: Resolving {0}{1}", source.ToString(), ""); Debug.Indent(); var r = ResolveToExpression.Translate(source, gc, cc, container); Debug.WriteLine("Expression Resolver: Result: {0}{1}", r == null ? "<null>" : r.ToString(), ""); return r; } finally { Debug.Unindent(); } }
// Dictionary has an odd not-implemented check to support custom dictionaries and therefore // needs a custom __eq__ / __ne__ implementation. public static string/*!*/ __repr__(CodeContext/*!*/ context, IDictionary<object, object> self) { List<object> infinite = PythonOps.GetAndCheckInfinite(self); if (infinite == null) { return "{...}"; } int index = infinite.Count; infinite.Add(self); try { StringBuilder buf = new StringBuilder(); buf.Append("{"); bool first = true; foreach (KeyValuePair<object, object> kv in self) { if (first) first = false; else buf.Append(", "); if (BaseSymbolDictionary.IsNullObject(kv.Key)) buf.Append("None"); else buf.Append(PythonOps.Repr(context, kv.Key)); buf.Append(": "); buf.Append(PythonOps.Repr(context, kv.Value)); } buf.Append("}"); return buf.ToString(); } finally { System.Diagnostics.Debug.Assert(index == infinite.Count - 1); infinite.RemoveAt(index); } }
public override object Build(CodeContext context, object[] args) { SymbolDictionary res = new SymbolDictionary(); for (int i = _argIndex; i < _argIndex + _names.Length; i++) { res.Add(_names[i - _argIndex], args[i]); } return res; }
public PythonDynamicStackFrame(CodeContext/*!*/ context, FunctionCode/*!*/ funcCode, int line) : base(GetMethod(context, funcCode), funcCode.co_name, funcCode.co_filename, line) { Assert.NotNull(context, funcCode); _context = context; _code = funcCode; }
public static object __new__(CodeContext context, PythonType type, object o) { object reversed; if (PythonOps.TryGetBoundAttr(context, o, "__reversed__", out reversed)) { return PythonCalls.Call(context, reversed); } object boundFunc; PythonTypeSlot getitem; PythonType pt = DynamicHelpers.GetPythonType(o); if(!pt.TryResolveSlot(context, "__getitem__", out getitem) || !getitem.TryGetValue(context, o, pt, out boundFunc) || o is PythonDictionary) { throw PythonOps.TypeError("argument to reversed() must be a sequence"); } int length; if (!DynamicHelpers.GetPythonType(o).TryGetLength(context, o, out length)) { throw PythonOps.TypeError("object of type '{0}' has no len()", DynamicHelpers.GetPythonType(o).Name); } if (type.UnderlyingSystemType == typeof(ReversedEnumerator)) { return new ReversedEnumerator((int)length, boundFunc); } return type.CreateInstance(context, length, getitem); }
public RuntimeScriptCode(PythonAst/*!*/ ast, CodeContext/*!*/ codeContext) : base(ast) { Debug.Assert(codeContext.GlobalScope.GetExtension(codeContext.LanguageContext.ContextId) != null); Debug.Assert(ast.Type == typeof(MSAst.Expression<Func<FunctionCode, object>>)); _optimizedContext = codeContext; }
/// <summary> /// Removes an attribute from the provided member /// </summary> public static void __delattr__(CodeContext/*!*/ context, object self, string name) { if (self is PythonType) { throw PythonOps.TypeError("can't apply this __delattr__ to type object"); } PythonOps.ObjectDeleteAttribute(context, self, name); }
/// <summary> /// Gateway into importing ... called from Ops. Performs the initial import of /// a module and returns the module. /// </summary> public static object Import(CodeContext/*!*/ context, string fullName, PythonTuple from, int level) { PythonContext pc = PythonContext.GetContext(context); if (level == -1) { // no specific level provided, call the 4 param version so legacy code continues to work return pc.OldImportSite.Target( pc.OldImportSite, context, FindImportFunction(context), fullName, Builtin.globals(context), context.Dict, from ); } // relative import or absolute import, in other words: // // from . import xyz // or // from __future__ import absolute_import return pc.ImportSite.Target( pc.ImportSite, context, FindImportFunction(context), fullName, Builtin.globals(context), context.Dict, from, level ); }
public static PythonTuple select(CodeContext/*!*/ context, object iwtd, object owtd, object ewtd, [DefaultParameterValue(null)] object timeout) { List readerList, writerList, errorList; Dictionary<Socket, object> readerOriginals, writerOriginals, errorOriginals; ProcessSocketSequence(context, iwtd, out readerList, out readerOriginals); ProcessSocketSequence(context, owtd, out writerList, out writerOriginals); ProcessSocketSequence(context, ewtd, out errorList, out errorOriginals); int timeoutMicroseconds; if (timeout == null) { // -1 doesn't really work as infinite, but it appears that any other negative value does timeoutMicroseconds = -2; } else { double timeoutSeconds; if (!Converter.TryConvertToDouble(timeout, out timeoutSeconds)) { throw PythonOps.TypeErrorForTypeMismatch("float or None", timeout); } timeoutMicroseconds = (int) (1000000 * timeoutSeconds); } try { Socket.Select(readerList, writerList, errorList, timeoutMicroseconds); } catch (ArgumentNullException) { throw MakeException(context, SocketExceptionToTuple(new SocketException((int)SocketError.InvalidArgument))); } catch (SocketException e) { throw MakeException(context, SocketExceptionToTuple(e)); } // Convert back to what the user originally passed in for (int i = 0; i < readerList.__len__(); i++) readerList[i] = readerOriginals[(Socket)readerList[i]]; for (int i = 0; i < writerList.__len__(); i++) writerList[i] = writerOriginals[(Socket)writerList[i]]; for (int i = 0; i < errorList.__len__(); i++) errorList[i] = errorOriginals[(Socket)errorList[i]]; return PythonTuple.MakeTuple(readerList, writerList, errorList); }
public static int field_size_limit(CodeContext /*!*/ context, int new_limit) { PythonContext ctx = PythonContext.GetContext(context); int old_limit = (int)ctx.GetModuleState(_fieldSizeLimitKey); ctx.SetModuleState(_fieldSizeLimitKey, new_limit); return old_limit; }
public StructType(CodeContext/*!*/ context, string name, PythonTuple bases, IAttributesCollection members) : base(context, name, bases, members) { foreach (PythonType pt in ResolutionOrder) { StructType st = pt as StructType; if (st != this && st != null) { st.EnsureFinal(); } UnionType ut = pt as UnionType; if (ut != null) { ut.EnsureFinal(); } } object pack; if (members.TryGetValue(SymbolTable.StringToId("_pack_"), out pack)) { if (!(pack is int) || ((int)pack < 0)) { throw PythonOps.ValueError("pack must be a non-negative integer"); } _pack = (int)pack; } object fields; if (members.TryGetValue(SymbolTable.StringToId("_fields_"), out fields)) { SetFields(fields); } // TODO: _anonymous_ }
public static object load_module(CodeContext/*!*/ context, string name, PythonFile file, string filename, PythonTuple/*!*/ description) { if (description == null) { throw PythonOps.TypeError("load_module() argument 4 must be 3-item sequence, not None"); } if (description.__len__() != 3) { throw PythonOps.TypeError("load_module() argument 4 must be sequence of length 3, not {0}", description.__len__()); } PythonContext pythonContext = PythonContext.GetContext(context); // already loaded? do reload() PythonModule module = pythonContext.GetModuleByName(name); if (module != null) { Importer.ReloadModule(context, module.Scope); return module.Scope; } int type = PythonContext.GetContext(context).ConvertToInt32(description[2]); switch (type) { case PythonSource: return LoadPythonSource(pythonContext, name, file, filename); case CBuiltin: return LoadBuiltinModule(context, name); case PackageDirectory: return LoadPackageDirectory(pythonContext, name, filename); default: throw PythonOps.TypeError("don't know how to import {0}, (type code {1}", name, type); } }
public static string oct(CodeContext context, object number) { if (number is int) { number = BigInteger.Create((int)number); } if (number is BigInteger) { BigInteger x = (BigInteger)number; if (x == 0) { return "0o0"; } else if (x > 0) { return "0o" + BigInteger.Create(x).ToString(8); } else { return "-0o" + BigInteger.Create(-x).ToString(8); } } object value; if (PythonTypeOps.TryInvokeUnaryOperator(context, number, Symbols.Index, out value)) { if (!(value is int) && !(value is BigInteger)) throw PythonOps.TypeError("index returned non-(int, long), got '{0}'", PythonTypeOps.GetName(value)); return oct(context, value); } throw PythonOps.TypeError("oct() argument cannot be interpreted as an index"); }
public static object proxy(CodeContext context, object @object, object callback) { if (PythonOps.IsCallable(context, @object)) { return weakcallableproxy.MakeNew(context, @object, callback); } else { return weakproxy.MakeNew(context, @object, callback); } }
public static object __cmp__(CodeContext/*!*/ context, IDictionary<object, object> self, object other) { IDictionary<object, object> oth = other as IDictionary<object, object>; // CompareTo is allowed to throw (string, int, etc... all do it if they don't get a matching type) if (oth == null) { object len, iteritems; if (!PythonOps.TryGetBoundAttr(DefaultContext.Default, other, Symbols.Length, out len) || !PythonOps.TryGetBoundAttr(DefaultContext.Default, other, SymbolTable.StringToId("iteritems"), out iteritems)) { return NotImplementedType.Value; } // user-defined dictionary... int lcnt = self.Count; int rcnt = Converter.ConvertToInt32(PythonOps.CallWithContext(DefaultContext.Default, len)); if (lcnt != rcnt) return lcnt > rcnt ? 1 : -1; return DictionaryOps.CompareToWorker(context, self, new List(PythonOps.CallWithContext(context, iteritems))); } CompareUtil.Push(self, oth); try { return DictionaryOps.CompareTo(context, self, oth); } finally { CompareUtil.Pop(self, oth); } }
private static Exception Error(CodeContext/*!*/ context, int errno, string/*!*/ message) { return PythonExceptions.CreateThrowable( (PythonType)PythonContext.GetContext(context).GetModuleState(_mmapErrorKey), errno, message ); }
public static RE_Pattern compile(CodeContext/*!*/ context, object pattern) { try { return new RE_Pattern(context, ValidatePattern(pattern), 0, true); } catch (ArgumentException e) { throw PythonExceptions.CreateThrowable(error(context), e.Message); } }
public static RE_Pattern compile(CodeContext/*!*/ context, object pattern, object flags) { try { return new RE_Pattern(context, ValidatePattern(pattern), PythonContext.GetContext(context).ConvertToInt32(flags), true); } catch (ArgumentException e) { throw PythonExceptions.CreateThrowable(error(context), e.Message); } }
public PythonDynamicStackFrame(CodeContext/*!*/ context, FunctionCode/*!*/ funcCode, MethodBase method, string funcName, string filename, int line) : base(method, funcName, filename, line) { Assert.NotNull(context, funcCode); _context = context; _code = funcCode; }
/// <summary> /// Convenience function for users to call directly /// </summary> public object GetValue(CodeContext context, object instance) { object value; if (TryGetValue(context, instance, DynamicHelpers.GetPythonType(instance), out value)) { return value; } throw new InvalidOperationException("cannot get field"); }
public object TryLookup( CodeContext mode, ImmutableLegacyPrefixList legacyPrefixes, Xex xex, byte opcode, out bool hasModRM, out int immediateSizeInBytes) { hasModRM = false; immediateSizeInBytes = 0; NasmInsnsEntry match = null; foreach (var entry in entries) { bool entryHasModRM; int entryImmediateSize; if (entry.Match(mode.GetDefaultAddressSize(), legacyPrefixes, xex, opcode, out entryHasModRM, out entryImmediateSize)) { if (match != null) { // If we match multiple, we should have the same response for each if (entryHasModRM != hasModRM) return false; if (entryImmediateSize != immediateSizeInBytes) return false; } hasModRM = entryHasModRM; immediateSizeInBytes = entryImmediateSize; match = entry; } } return match; }
public static PythonTuple CreatePipe( CodeContext context, object pSec /*Python passes None*/, int bufferSize) { IntPtr hReadPipe; IntPtr hWritePipe; SECURITY_ATTRIBUTES pSecA = new SECURITY_ATTRIBUTES(); pSecA.nLength = Marshal.SizeOf(pSecA); if (pSec != null) { /* If pSec paseed in from Python is not NULL * there needs to be some conversion done here...*/ } // TODO: handle failures CreatePipePI( out hReadPipe, out hWritePipe, ref pSecA, (uint)bufferSize); return PythonTuple.MakeTuple( new PythonSubprocessHandle(hReadPipe), new PythonSubprocessHandle(hWritePipe) ); }
public StringFormatter(CodeContext/*!*/ context, string str, object data, bool isUnicode) { _str = str; _data = data; _context = context; _isUnicodeString = isUnicode; }
public _FileIO(CodeContext/*!*/ context, int fd, [DefaultParameterValue("r")]string mode, [DefaultParameterValue(true)]bool closefd) { if (fd < 0) { throw PythonOps.ValueError("fd must be >= 0"); } PythonContext pc = PythonContext.GetContext(context); _FileIO file = (_FileIO)pc.FileManager.GetObjectFromId(pc, fd); Console.WriteLine(file); _context = pc; switch (mode) { case "r": _mode = "rb"; break; case "w": _mode = "wb"; break; case "a": _mode = "w"; break; case "r+": case "+r": _mode = "rb+"; break; case "w+": case "+w": _mode = "rb+"; break; case "a+": case "+a": _mode = "r+"; break; default: BadMode(mode); break; } _readStream = file._readStream; _writeStream = file._writeStream; _closefd = closefd; }
/// <summary> /// Called from generated code when we are supposed to print an expression value /// </summary> public static void PrintExpressionValue(CodeContext/*!*/ context, object value) { Console.WriteLine(value); //PythonContext pc = PythonContext.GetContext(context); //object dispHook = pc.GetSystemStateValue("displayhook"); //pc.CallWithContext(context, dispHook, value); }
public LuaScriptCode(CodeContext context, SourceUnit sourceUnit, Expression<Func<IDynamicMetaObjectProvider, dynamic>> chunk) : base(sourceUnit) { Contract.Requires(chunk != null); Context = context; _exprLambda = chunk; }
public static object Call(CodeContext/*!*/ context, TypeGroup/*!*/ self, params object[] args) { return PythonCalls.Call( context, DynamicHelpers.GetPythonTypeFromType(self.NonGenericType), args ?? ArrayUtils.EmptyObjects ); }
public void __init__(CodeContext context, string filename, [DefaultParameterValue("r")]string mode, [DefaultParameterValue(0)]int buffering, [DefaultParameterValue(DEFAULT_COMPRESSLEVEL)]int compresslevel) { var pythonContext = PythonContext.GetContext(context); this.buffering = buffering; this.compresslevel = compresslevel; if (!mode.Contains("b") && !mode.Contains("U")) { // bz2 files are always written in binary mode, unless they are in univeral newline mode mode = mode + 'b'; } if (mode.Contains("w")) { var underlyingStream = File.Open(filename, FileMode.Create, FileAccess.Write); if (mode.Contains("p")) { this.bz2Stream = new ParallelBZip2OutputStream(underlyingStream); } else { this.bz2Stream = new BZip2OutputStream(underlyingStream); } } else { this.bz2Stream = new BZip2InputStream(File.OpenRead(filename)); } this.__init__(bz2Stream, pythonContext.DefaultEncoding, filename, mode); }
/// <summary> /// Python ctor - maps to function.__new__ /// /// y = func(x.__code__, globals(), 'foo', None, (a, )) /// </summary> public PythonFunction(CodeContext context, FunctionCode code, PythonDictionary globals, string name, PythonTuple defaults, PythonTuple closure) { if (closure != null && closure.__len__() != 0) { throw new NotImplementedException("non empty closure argument is not supported"); } if (globals == context.GlobalDict) { _module = context.Module.GetName(); _context = context; } else { _module = null; _context = new CodeContext(new PythonDictionary(), new ModuleContext(globals, DefaultContext.DefaultPythonContext)); } _defaults = defaults == null ? ArrayUtils.EmptyObjects : defaults.ToArray(); _code = code; _name = name; _doc = code._initialDoc; Closure = null; var scopeStatement = _code.PythonCode; if (scopeStatement.IsClosure) { throw new NotImplementedException("code containing closures is not supported"); } scopeStatement.RewriteBody(FunctionDefinition.ArbitraryGlobalsVisitorInstance); _compat = CalculatedCachedCompat(); }
public compress(CodeContext /*!*/ context, [NotNull] object data, [NotNull] object selectors) { EnsureIterator(context, data); EnsureIterator(context, selectors); InnerEnumerator = LazyYielder(data, selectors); }
public override void Execute(CodeContext context) => PropertyDefSettingsCommand.Execute(undoCommandService, appService, context.Nodes);
public override bool IsEnabled(CodeContext context) => PropertyDefSettingsCommand.CanExecute(context.Nodes);
public override void Execute(CodeContext context) => CreatePropertyDefCommand.Execute(undoCommandService, appService, context.Nodes);
public override bool IsEnabled(CodeContext context) => context.IsDefinition && context.Nodes.Length == 1 && context.Nodes[0] is ITypeNode;
public ifilterfalse(CodeContext /*!*/ context, object predicate, object iterable) { _context = context; InnerEnumerator = Yielder(predicate, PythonOps.GetEnumerator(iterable)); }
public groupby(CodeContext /*!*/ context, object iterable) { InnerEnumerator = Yielder(PythonOps.GetEnumerator(iterable)); _context = context; }
private static Exception ErrorDecoding(CodeContext context, params object[] args) { return PythonExceptions.CreateThrowable(SSLError(context), ArrayUtils.Insert("Error decoding PEM-encoded file ", args)); }
public static PythonDictionary _test_decode_cert(CodeContext context, string filename, bool complete=false) { var cert = ReadCertificate(context, filename); return CertificateToPython(context, cert, complete); }
public starmap(CodeContext context, object function, object iterable) { InnerEnumerator = Yielder(context, function, PythonOps.GetEnumerator(iterable)); }
public object _wrap_socket(CodeContext context, [DefaultParameterValue(null)] PythonSocket.socket sock, [DefaultParameterValue(false)] bool server_side, [DefaultParameterValue(null)] string server_hostname, [DefaultParameterValue(null)] object ssl_sock) { return new PythonSocket.ssl(context, sock, server_side, null, _cafile, verify_mode, protocol | options, null, _cert_store); }
internal static PythonDictionary CertificateToPython(CodeContext context, X509Certificate cert, bool complete) { return CertificateToPython(context, new X509Certificate2(cert.GetRawCertData()), complete); }
public void set_ciphers(CodeContext context, string ciphers) { }
internal static PythonType SSLError(CodeContext/*!*/ context) { return (PythonType)context.LanguageContext.GetModuleState("SSLError"); }
public string /*!*/ __repr__(CodeContext /*!*/ context) { return("NotImplemented"); }
public void set_default_verify_paths(CodeContext context) { }
public object keys(CodeContext context) { return(new List(_dt.GetMemberDictionary(context, false).Keys)); }
public SetMemberBinderHelper(CodeContext context, OldSetMemberAction action, object[] args, RuleBuilder rule) : base(context, action, args, rule) { }
public string /*!*/ __str__(CodeContext /*!*/ context) { return(DictionaryOps.__repr__(context, this)); }
public string /*!*/ __repr__(CodeContext /*!*/ context) { return("Ellipsis"); }
public int __len__(CodeContext context) { return(_dt.GetMemberDictionary(context, false).Count); }
public bool has_key(CodeContext /*!*/ context, object key) { object dummy; return(TryGetValue(context, key, out dummy)); }
public PythonDictionary copy(CodeContext /*!*/ context) { return(new PythonDictionary(context, this)); }
public bool __contains__(CodeContext /*!*/ context, object value) { return(has_key(context, value)); }
public static IDictionary Get__dict__(CodeContext context, TypeTracker self) { return(new DictProxy(DynamicHelpers.GetPythonTypeFromType(self.Type))); }
public IEnumerator itervalues(CodeContext /*!*/ context) { return(new DictionaryValueEnumerator(_dt.GetMemberDictionary(context, false)._storage)); }
public static object Call(CodeContext /*!*/ context, Delegate @delegate, params object[] args) { return(PythonContext.GetContext(context).CallSplat(@delegate, args)); }
public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts) { _codeContext = codeContext; for (var i = 0; i < _values.Length; i++) { Parser.Build(ref _values[i], 2, variables, codeContext | CodeContext.InExpression, message, stats, opts); } for (var i = 0; i < _computedProperties.Length; i++) { var key = _computedProperties[i].Key; Parser.Build(ref key, 2, variables, codeContext | CodeContext.InExpression, message, stats, opts); var value = _computedProperties[i].Value; Parser.Build(ref value, 2, variables, codeContext | CodeContext.InExpression, message, stats, opts); _computedProperties[i] = new KeyValuePair <Expression, Expression>(key, value); } return(false); }
public string /*!*/ __repr__(CodeContext /*!*/ context) { return(string.Format("<event# {0} on {1}>", Info.Name, Info.DeclaringType.Name)); }
public static object Call(CodeContext /*!*/ context, Delegate @delegate, [ParamDictionary] IDictionary <object, object> dict, params object[] args) { return(PythonContext.GetContext(context).CallWithKeywords(@delegate, args, dict)); }