Repository navigation
Expand file tree
/
Copy pathBuiltin.cs
More file actions
2493 lines (2103 loc) · 97.4 KB
/
Copy pathBuiltin.cs
File metadata and controls
2493 lines (2103 loc) · 97.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Compiler;
using IronPython.Compiler.Ast;
using IronPython.Runtime;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
#if FEATURE_NUMERICS
using System.Numerics;
#else
using Microsoft.Scripting.Math;
using Complex = Microsoft.Scripting.Math.Complex64;
#endif
[assembly: PythonModule("builtins", typeof(IronPython.Modules.Builtin))]
namespace IronPython.Modules {
[Documentation("")] // Documentation suppresses XML Doc on startup.
public static partial class Builtin {
public const string __doc__ = "Provides access to commonly used built-in functions, exception objects, etc...";
public const object __package__ = null;
public const string __name__ = "builtins";
public static object True {
get {
return ScriptingRuntimeHelpers.True;
}
}
public static object False {
get {
return ScriptingRuntimeHelpers.False;
}
}
// This will always stay null
public static readonly object None;
public static IronPython.Runtime.Types.Ellipsis Ellipsis {
get {
return IronPython.Runtime.Types.Ellipsis.Value;
}
}
public static NotImplementedType NotImplemented {
get {
return NotImplementedType.Value;
}
}
public static object exit {
get {
return "Use Ctrl-Z plus Return to exit";
}
}
public static object quit {
get {
return "Use Ctrl-Z plus Return to exit";
}
}
[Documentation("__import__(name) -> module\n\nImport a module.")]
[LightThrowing]
public static object __import__(CodeContext/*!*/ context, string name) {
return __import__(context, name, null, null, null, -1);
}
[Documentation("__import__(name, globals, locals, fromlist, level) -> module\n\nImport a module.")]
[LightThrowing]
public static object __import__(CodeContext/*!*/ context, string name, [DefaultParameterValue(null)]object globals, [DefaultParameterValue(null)]object locals, [DefaultParameterValue(null)]object fromlist, [DefaultParameterValue(-1)]int level) {
if (fromlist is string || fromlist is Extensible<string>) {
fromlist = new List<object> { fromlist };
}
IList from = fromlist as IList;
PythonContext pc = PythonContext.GetContext(context);
object ret = Importer.ImportModule(context, globals, name, from != null && from.Count > 0, level);
if (ret == null) {
return LightExceptions.Throw(PythonOps.ImportError("No module named {0}", name));
}
PythonModule mod = ret as PythonModule;
if (mod != null && from != null) {
string strAttrName;
for (int i = 0; i < from.Count; i++) {
object attrName = from[i];
if (pc.TryConvertToString(attrName, out strAttrName) &&
!String.IsNullOrEmpty(strAttrName) &&
strAttrName != "*") {
try {
Importer.ImportFrom(context, mod, strAttrName);
} catch (ImportException) {
continue;
}
}
}
}
return ret;
}
[Documentation("abs(number) -> number\n\nReturn the absolute value of the argument.")]
public static object abs(CodeContext/*!*/ context, object o) {
if (o is int) return Int32Ops.Abs((int)o);
if (o is long) return Int64Ops.Abs((long)o);
if (o is double) return DoubleOps.Abs((double)o);
if (o is bool) return (((bool)o) ? 1 : 0);
if (o is BigInteger) return BigIntegerOps.__abs__((BigInteger)o);
if (o is Complex) return ComplexOps.Abs((Complex)o);
object value;
if (PythonTypeOps.TryInvokeUnaryOperator(context, o, "__abs__", out value)) {
return value;
}
throw PythonOps.TypeError("bad operand type for abs(): '{0}'", PythonTypeOps.GetName(o));
}
public static bool all(object x) {
IEnumerator i = PythonOps.GetEnumerator(x);
while (i.MoveNext()) {
if (!PythonOps.IsTrue(i.Current)) return false;
}
return true;
}
public static bool any(object x) {
IEnumerator i = PythonOps.GetEnumerator(x);
while (i.MoveNext()) {
if (PythonOps.IsTrue(i.Current)) return true;
}
return false;
}
[Documentation("apply(object[, args[, kwargs]]) -> value\n\nDeprecated.\nInstead, use:\n function(*args, **keywords).")]
public static object apply(CodeContext/*!*/ context, object func) {
return PythonOps.CallWithContext(context, func);
}
public static object apply(CodeContext/*!*/ context, object func, object args) {
return PythonOps.CallWithArgsTupleAndContext(context, func, ArrayUtils.EmptyObjects, args);
}
public static object apply(CodeContext/*!*/ context, object func, object args, object kws) {
return context.LanguageContext.CallWithKeywords(func, args, kws);
}
public static PythonType basestring {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(string));
}
}
public static string bin(int number) {
return Int32Ops.ToBinary(number);
}
public static string bin(Index number) {
return Int32Ops.ToBinary(Converter.ConvertToIndex(number));
}
public static string bin(BigInteger number) {
return BigIntegerOps.ToBinary(number);
}
public static string bin(double number) {
throw PythonOps.TypeError("'float' object cannot be interpreted as an index");
}
public static PythonType @bool {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(bool));
}
}
public static PythonType buffer {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(PythonBuffer));
}
}
public static PythonType bytes {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(Bytes));
}
}
public static PythonType bytearray {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(ByteArray));
}
}
[Documentation("callable(object) -> bool\n\nReturn whether the object is callable (i.e., some kind of function).")]
[Python3Warning("callable() is removed in 3.x. instead call hasattr(obj, '__call__')")]
public static bool callable(CodeContext/*!*/ context, object o) {
return PythonOps.IsCallable(context, o);
}
[Documentation("chr(i) -> character\n\nReturn a string of one character with ordinal i; 0 <= i< 256.")]
[LightThrowing]
public static object chr(int value) {
if (value < 0 || value > 0xFF) {
return LightExceptions.Throw(PythonOps.ValueError("{0} is not in required range", value));
}
return ScriptingRuntimeHelpers.CharToString((char)value);
}
internal static object TryCoerce(CodeContext/*!*/ context, object x, object y) {
PythonTypeSlot pts;
PythonType xType = DynamicHelpers.GetPythonType(x);
if (xType.TryResolveSlot(context, "__coerce__", out pts)) {
object callable;
if (pts.TryGetValue(context, x, xType, out callable)) {
return PythonCalls.Call(context, callable, y);
}
}
return NotImplementedType.Value;
}
[Documentation("coerce(x, y) -> (x1, y1)\n\nReturn a tuple consisting of the two numeric arguments converted to\na common type. If coercion is not possible, raise TypeError.")]
public static object coerce(CodeContext/*!*/ context, object x, object y) {
object converted;
if (x == null && y == null) {
return PythonTuple.MakeTuple(null, null);
}
converted = TryCoerce(context, x, y);
if (converted != null && converted != NotImplementedType.Value) {
return converted;
}
converted = TryCoerce(context, y, x);
if (converted != null && converted != NotImplementedType.Value) {
PythonTuple pt = converted as PythonTuple;
if (pt != null && pt.Count == 2) {
return PythonTuple.MakeTuple(pt[1], pt[0]);
}
}
throw PythonOps.TypeError("coercion failed");
}
[Documentation("compile a unit of source code.\n\nThe source can be compiled either as exec, eval, or single.\nexec compiles the code as if it were a file\neval compiles the code as if were an expression\nsingle compiles a single statement\n\nsource can either be a string or an AST object")]
public static object compile(CodeContext/*!*/ context, object source, string filename, string mode, [DefaultParameterValue(null)]object flags, [DefaultParameterValue(null)]object dont_inherit) {
bool astOnly = false;
int iflags = flags != null ? Converter.ConvertToInt32(flags) : 0;
if ((iflags & _ast.PyCF_ONLY_AST) != 0) {
astOnly = true;
iflags &= ~_ast.PyCF_ONLY_AST;
}
if (mode != "exec" && mode != "eval" && mode != "single") {
throw PythonOps.ValueError("compile() arg 3 must be 'exec' or 'eval' or 'single'");
}
if (source is _ast.AST) {
if (astOnly) {
return source;
} else {
PythonAst ast = _ast.ConvertToPythonAst(context, (_ast.AST) source);
ast.Bind();
ScriptCode code = ast.ToScriptCode();
return ((RunnableScriptCode)code).GetFunctionCode(true);
}
}
string text;
if (source is string)
text = (string)source;
else if (source is PythonBuffer)
text = ((PythonBuffer)source).ToString();
else if (source is ByteArray)
text = ((ByteArray)source).ToString();
else if (source is Bytes)
text = ((Bytes)source).ToString();
else
// cpython accepts either AST or readable buffer object
throw PythonOps.TypeError("srouce can be either AST or string, actual argument: {0}", source.GetType());
if (text.IndexOf('\0') != -1) {
throw PythonOps.TypeError("compile() expected string without null bytes");
}
text = RemoveBom(text);
bool inheritContext = GetCompilerInheritance(dont_inherit);
CompileFlags cflags = GetCompilerFlags(iflags);
PythonCompilerOptions opts = GetRuntimeGeneratedCodeCompilerOptions(context, inheritContext, cflags);
if ((cflags & CompileFlags.CO_DONT_IMPLY_DEDENT) != 0) {
opts.DontImplyDedent = true;
}
SourceUnit sourceUnit = null;
switch (mode) {
case "exec": sourceUnit = context.LanguageContext.CreateSnippet(text, filename, SourceCodeKind.Statements); break;
case "eval": sourceUnit = context.LanguageContext.CreateSnippet(text, filename, SourceCodeKind.Expression); break;
case "single": sourceUnit = context.LanguageContext.CreateSnippet(text, filename, SourceCodeKind.InteractiveCode); break;
}
return !astOnly ?
(object)FunctionCode.FromSourceUnit(sourceUnit, opts, true) :
(object)_ast.BuildAst(context, sourceUnit, opts, mode);
}
private static string RemoveBom(string source) {
// skip BOM (TODO: this is ugly workaround that is in fact not strictly correct, we need binary strings to handle it correctly)
if (source.StartsWith("\u00ef\u00bb\u00bf", StringComparison.Ordinal)) {
source = source.Substring(3, source.Length - 3);
}
return source;
}
public static PythonType classmethod {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(classmethod));
}
}
public static int cmp(CodeContext/*!*/ context, object x, object y) {
return PythonOps.Compare(context, x, y);
}
// having a cmp overload for double would be nice, but it breaks:
// x = 1e66666
// y = x/x
// cmp(y,y)
// which returns 0 because id(y) == id(y). If we added a double overload
// we lose object identity.
public static int cmp(CodeContext/*!*/ context, int x, int y) {
return Int32Ops.Compare(x, y);
}
public static int cmp(CodeContext/*!*/ context, [NotNull]BigInteger x, [NotNull]BigInteger y) {
if ((object)x == (object)y) {
return 0;
}
return BigIntegerOps.Compare(x, y);
}
public static int cmp(CodeContext/*!*/ context, double x, [NotNull]BigInteger y) {
return -BigIntegerOps.Compare(y, x);
}
public static int cmp(CodeContext/*!*/ context, [NotNull]BigInteger x, double y) {
return BigIntegerOps.Compare(x, y);
}
public static int cmp(CodeContext/*!*/ context, [NotNull]string x, [NotNull]string y) {
if ((object)x != (object)y) {
int res = string.CompareOrdinal(x, y);
if (res >= 1) {
return 1;
} else if (res <= -1) {
return -1;
}
}
return 0;
}
#if FEATURE_SORTKEY
public static int cmp(CodeContext/*!*/ context, [NotNull]SortKey x, [NotNull]SortKey y) {
return SortKey.Compare(x, y);
}
#endif
public static int cmp(CodeContext/*!*/ context, [NotNull]PythonTuple x, [NotNull]PythonTuple y) {
if ((object)x == (object)y) {
return 0;
}
return x.CompareTo(y);
}
public static PythonType complex {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(Complex));
}
}
public static void delattr(CodeContext/*!*/ context, object o, string name) {
PythonOps.DeleteAttr(context, o, name);
}
public static PythonType dict {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(PythonDictionary));
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public static List dir(CodeContext/*!*/ context) {
List res = PythonOps.MakeListFromSequence(context.Dict.Keys);
res.sort(context);
return res;
}
public static List dir(CodeContext/*!*/ context, object o) {
IList<object> ret = PythonOps.GetAttrNames(context, o);
List lret = new List(ret);
lret.sort(context);
return lret;
}
public static object divmod(CodeContext/*!*/ context, object x, object y) {
Debug.Assert(NotImplementedType.Value != null);
return PythonContext.GetContext(context).DivMod(x, y);
}
public static PythonType enumerate {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(Enumerate));
}
}
public static object eval(CodeContext/*!*/ context, FunctionCode code) {
Debug.Assert(context != null);
if (code == null) throw PythonOps.TypeError("eval() argument 1 must be string or code object");
return eval(context, code, null);
}
public static object eval(CodeContext/*!*/ context, FunctionCode code, PythonDictionary globals) {
Debug.Assert(context != null);
if (code == null) throw PythonOps.TypeError("eval() argument 1 must be string or code object");
return eval(context, code, globals, globals);
}
public static object eval(CodeContext/*!*/ context, FunctionCode code, PythonDictionary globals, object locals) {
Debug.Assert(context != null);
if (code == null) throw PythonOps.TypeError("eval() argument 1 must be string or code object");
return code.Call(GetExecEvalScopeOptional(context, globals, locals, false));
}
internal static PythonDictionary GetAttrLocals(CodeContext/*!*/ context, object locals) {
PythonDictionary attrLocals = null;
if (locals == null) {
if (context.IsTopLevel) {
attrLocals = context.Dict;
}
} else {
attrLocals = locals as PythonDictionary ?? new PythonDictionary(new ObjectAttributesAdapter(context, locals));
}
return attrLocals;
}
[LightThrowing]
public static object eval(CodeContext/*!*/ context, string expression) {
Debug.Assert(context != null);
if (expression == null) throw PythonOps.TypeError("eval() argument 1 must be string or code object");
return eval(context, expression, globals(context), locals(context));
}
[LightThrowing]
public static object eval(CodeContext/*!*/ context, string expression, PythonDictionary globals) {
Debug.Assert(context != null);
if (expression == null) throw PythonOps.TypeError("eval() argument 1 must be string or code object");
return eval(context, expression, globals, globals);
}
[LightThrowing]
public static object eval(CodeContext/*!*/ context, string expression, PythonDictionary globals, object locals) {
Debug.Assert(context != null);
if (expression == null) throw PythonOps.TypeError("eval() argument 1 must be string or code object");
if (locals != null && PythonOps.IsMappingType(context, locals) == ScriptingRuntimeHelpers.False) {
throw PythonOps.TypeError("locals must be mapping");
}
expression = RemoveBom(expression);
var scope = GetExecEvalScopeOptional(context, globals, locals, false);
var pythonContext = PythonContext.GetContext(context);
// TODO: remove TrimStart
var sourceUnit = pythonContext.CreateSnippet(expression.TrimStart(' ', '\t'), SourceCodeKind.Expression);
var compilerOptions = GetRuntimeGeneratedCodeCompilerOptions(context, true, 0);
compilerOptions.Module |= ModuleOptions.LightThrow;
compilerOptions.Module &= ~ModuleOptions.ModuleBuiltins;
var code = FunctionCode.FromSourceUnit(sourceUnit, compilerOptions, false);
return code.Call(scope);
}
public static void execfile(CodeContext/*!*/ context, object/*!*/ filename) {
execfile(context, filename, null, null);
}
public static void execfile(CodeContext/*!*/ context, object/*!*/ filename, object globals) {
execfile(context, filename, globals, null);
}
public static void execfile(CodeContext/*!*/ context, object/*!*/ filename, object globals, object locals) {
if (filename == null) {
throw PythonOps.TypeError("execfile() argument 1 must be string, not None");
}
PythonDictionary g = globals as PythonDictionary;
if (g == null && globals != null) {
throw PythonOps.TypeError("execfile() arg 2 must be dictionary");
}
PythonDictionary l = locals as PythonDictionary;
if (l == null && locals != null) {
throw PythonOps.TypeError("execfile() arg 3 must be dictionary");
}
if (l == null) {
l = g;
}
var execScope = GetExecEvalScopeOptional(context, g, l, true);
string path = Converter.ConvertToString(filename);
PythonContext pc = PythonContext.GetContext(context);
if (!pc.DomainManager.Platform.FileExists(path)) {
throw PythonOps.IOError("execfile: specified file doesn't exist");
}
SourceUnit sourceUnit = pc.CreateFileUnit(path, pc.DefaultEncoding, SourceCodeKind.Statements);
FunctionCode code;
var options = GetRuntimeGeneratedCodeCompilerOptions(context, true, 0);
//always generate an unoptimized module since we run these against a dictionary namespace
options.Module &= ~ModuleOptions.Optimized;
try {
code = FunctionCode.FromSourceUnit(sourceUnit, options, false);
} catch (UnauthorizedAccessException x) {
throw PythonOps.IOError(x);
}
// Do not attempt evaluation mode for execfile
code.Call(execScope);
}
public static PythonType file {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(PythonFile));
}
}
public static string filter(CodeContext/*!*/ context, object function, [NotNull]string list) {
if (function == null) return list;
if (list == null) throw PythonOps.TypeError("NoneType is not iterable");
StringBuilder sb = new StringBuilder();
foreach (char c in list) {
if (PythonOps.IsTrue(PythonCalls.Call(context, function, ScriptingRuntimeHelpers.CharToString(c)))) sb.Append(c);
}
return sb.ToString();
}
public static string filter(CodeContext/*!*/ context, object function, [NotNull]ExtensibleString list) {
StringBuilder sb = new StringBuilder();
IEnumerator e = PythonOps.GetEnumerator(list);
while (e.MoveNext()) {
object o = e.Current;
object t = (function != null) ? PythonCalls.Call(context, function, o) : o;
if (PythonOps.IsTrue(t)) {
sb.Append(Converter.ConvertToString(o));
}
}
return sb.ToString();
}
/// <summary>
/// Specialized version because enumerating tuples by Python's definition
/// doesn't call __getitem__, but filter does!
/// </summary>
public static PythonTuple filter(CodeContext/*!*/ context, object function, [NotNull]PythonTuple tuple) {
List<object> res = new List<object>(tuple.__len__());
for (int i = 0; i < tuple.__len__(); i++) {
object obj = tuple[i];
object t = (function != null) ? PythonCalls.Call(context, function, obj) : obj;
if (PythonOps.IsTrue(t)) {
res.Add(obj);
}
}
return PythonTuple.MakeTuple(res.ToArray());
}
public static List filter(CodeContext/*!*/ context, object function, object list) {
if (list == null) throw PythonOps.TypeError("NoneType is not iterable");
List ret = new List();
IEnumerator i = PythonOps.GetEnumerator(list);
while (i.MoveNext()) {
if (function == null) {
if (PythonOps.IsTrue(i.Current)) ret.AddNoLock(i.Current);
} else {
if (PythonOps.IsTrue(PythonCalls.Call(context, function, i.Current))) ret.AddNoLock(i.Current);
}
}
return ret;
}
public static PythonType @float {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(double));
}
}
public static string format(CodeContext/*!*/ context, object argValue, [DefaultParameterValue("")]string formatSpec) {
object res, formatMethod;
OldInstance oi = argValue as OldInstance;
if (oi != null && oi.TryGetBoundCustomMember(context, "__format__", out formatMethod)) {
res = PythonOps.CallWithContext(context, formatMethod, formatSpec);
} else {
// call __format__ with the format spec (__format__ is defined on object, so this always succeeds)
PythonTypeOps.TryInvokeBinaryOperator(
context,
argValue,
formatSpec,
"__format__",
out res);
}
string strRes = res as string;
if (strRes == null) {
throw PythonOps.TypeError("{0}.__format__ must return string or unicode, not {1}", PythonTypeOps.GetName(argValue), PythonTypeOps.GetName(res));
}
return strRes;
}
public static object getattr(CodeContext/*!*/ context, object o, string name) {
return PythonOps.GetBoundAttr(context, o, name);
}
public static object getattr(CodeContext/*!*/ context, object o, string name, object def) {
object ret;
if (PythonOps.TryGetBoundAttr(context, o, name, out ret)) return ret;
else return def;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public static PythonDictionary globals(CodeContext/*!*/ context) {
return context.ModuleContext.Globals;
}
public static bool hasattr(CodeContext/*!*/ context, object o, string name) {
return PythonOps.HasAttr(context, o, name);
}
public static int hash(CodeContext/*!*/ context, object o) {
return PythonContext.Hash(o);
}
public static int hash(CodeContext/*!*/ context, [NotNull]PythonTuple o) {
return ((IStructuralEquatable)o).GetHashCode(PythonContext.GetContext(context).EqualityComparerNonGeneric);
}
// this is necessary because overload resolution selects the int form.
public static int hash(CodeContext/*!*/ context, char o) {
return PythonContext.Hash(o);
}
public static int hash(CodeContext/*!*/ context, int o) {
return o;
}
public static int hash(CodeContext/*!*/ context, [NotNull]string o) {
return o.GetHashCode();
}
// this is necessary because overload resolution will coerce extensible strings to strings.
public static int hash(CodeContext/*!*/ context, [NotNull]ExtensibleString o) {
return hash(context, (object)o);
}
public static int hash(CodeContext/*!*/ context, [NotNull]BigInteger o) {
return BigIntegerOps.__hash__(o);
}
public static int hash(CodeContext/*!*/ context, [NotNull]Extensible<BigInteger> o) {
return hash(context, (object)o);
}
public static int hash(CodeContext/*!*/ context, double o) {
return DoubleOps.__hash__(o);
}
public static void help(CodeContext/*!*/ context, object o) {
StringBuilder doc = new StringBuilder();
List<object> doced = new List<object>(); // document things only once
help(context, doced, doc, 0, o);
if (doc.Length == 0) {
if (!(o is string)) {
help(context, DynamicHelpers.GetPythonType(o));
return;
}
doc.Append("no documentation found for ");
doc.Append(PythonOps.Repr(context, o));
}
string[] strings = doc.ToString().Split('\n');
for (int i = 0; i < strings.Length; i++) {
/* should read only a key, not a line, but we don't seem
* to have a way to do that...
if ((i % Console.WindowHeight) == 0) {
Ops.Print(context.SystemState, "-- More --");
Ops.ReadLineFromSrc(context.SystemState);
}*/
PythonOps.Print(context, strings[i]);
}
}
private static void help(CodeContext/*!*/ context, List<object>/*!*/ doced, StringBuilder/*!*/ doc, int indent, object obj) {
PythonType type;
BuiltinFunction builtinFunction;
PythonFunction function;
BuiltinMethodDescriptor methodDesc;
Method method;
string strVal;
PythonModule pyModule;
OldClass oldClass;
if (doced.Contains(obj)) return; // document things only once
doced.Add(obj);
if ((strVal = obj as string) != null) {
if (indent != 0) return;
// try and find things that string could refer to,
// then call help on them.
foreach (object module in PythonContext.GetContext(context).SystemStateModules.Values) {
IList<object> attrs = PythonOps.GetAttrNames(context, module);
List candidates = new List();
foreach (string s in attrs) {
if (s == strVal) {
object modVal;
if (!PythonOps.TryGetBoundAttr(context, module, strVal, out modVal))
continue;
candidates.append(modVal);
}
}
// favor types, then built-in functions, then python functions,
// and then only display help for one.
type = null;
builtinFunction = null;
function = null;
for (int i = 0; i < candidates.__len__(); i++) {
if ((type = candidates[i] as PythonType) != null) {
break;
}
if (builtinFunction == null && (builtinFunction = candidates[i] as BuiltinFunction) != null)
continue;
if (function == null && (function = candidates[i] as PythonFunction) != null)
continue;
}
if (type != null) help(context, doced, doc, indent, type);
else if (builtinFunction != null) help(context, doced, doc, indent, builtinFunction);
else if (function != null) help(context, doced, doc, indent, function);
}
} else if ((type = obj as PythonType) != null) {
// find all the functions, and display their
// documentation
if (indent == 0) {
doc.AppendFormat("Help on {0} in module {1}\n\n", type.Name, PythonOps.GetBoundAttr(context, type, "__module__"));
}
PythonTypeSlot dts;
if (type.TryResolveSlot(context, "__doc__", out dts)) {
object docText;
if (dts.TryGetValue(context, null, type, out docText) && docText != null)
AppendMultiLine(doc, docText.ToString() + Environment.NewLine, indent);
AppendIndent(doc, indent);
doc.AppendLine("Data and other attributes defined here:");
AppendIndent(doc, indent);
doc.AppendLine();
}
List names = type.GetMemberNames(context);
names.sort(context);
foreach (string name in names) {
if (name == "__class__") continue;
PythonTypeSlot value;
object val;
if (type.TryLookupSlot(context, name, out value) &&
value.TryGetValue(context, null, type, out val)) {
help(context, doced, doc, indent + 1, val);
}
}
} else if ((methodDesc = obj as BuiltinMethodDescriptor) != null) {
if (indent == 0) doc.AppendFormat("Help on method-descriptor {0}\n\n", methodDesc.__name__);
AppendIndent(doc, indent);
doc.Append(methodDesc.__name__);
doc.Append("(...)\n");
AppendMultiLine(doc, methodDesc.__doc__, indent + 1);
} else if ((builtinFunction = obj as BuiltinFunction) != null) {
if (indent == 0) doc.AppendFormat("Help on built-in function {0}\n\n", builtinFunction.Name);
AppendIndent(doc, indent);
doc.Append(builtinFunction.Name);
doc.Append("(...)\n");
AppendMultiLine(doc, builtinFunction.__doc__, indent + 1);
} else if ((function = obj as PythonFunction) != null) {
if (indent == 0) doc.AppendFormat("Help on function {0} in module {1}:\n\n", function.__name__, function.__module__);
AppendIndent(doc, indent);
doc.Append(function.GetSignatureString());
string pfDoc = Converter.ConvertToString(function.__doc__);
if (!String.IsNullOrEmpty(pfDoc)) {
AppendMultiLine(doc, pfDoc, indent);
}
} else if ((method = obj as Method) != null && ((function = method.im_func as PythonFunction) != null)) {
if (indent == 0) doc.AppendFormat("Help on method {0} in module {1}:\n\n", function.__name__, function.__module__);
AppendIndent(doc, indent);
doc.Append(function.GetSignatureString());
if (method.im_self == null) {
doc.AppendFormat(" unbound {0} method\n", PythonOps.ToString(method.im_class));
} else {
doc.AppendFormat(" method of {0} instance\n", PythonOps.ToString(method.im_class));
}
string pfDoc = Converter.ConvertToString(function.__doc__);
if (!String.IsNullOrEmpty(pfDoc)) {
AppendMultiLine(doc, pfDoc, indent);
}
} else if ((pyModule = obj as PythonModule) != null) {
foreach (string name in pyModule.__dict__.Keys) {
if (name == "__class__" || name == "__builtins__") continue;
object value;
if (pyModule.__dict__.TryGetValue(name, out value)) {
help(context, doced, doc, indent + 1, value);
}
}
} else if ((oldClass = obj as OldClass) != null) {
if (indent == 0) {
doc.AppendFormat("Help on {0} in module {1}\n\n", oldClass.Name, PythonOps.GetBoundAttr(context, oldClass, "__module__"));
}
object docText;
if (oldClass.TryLookupSlot("__doc__", out docText) && docText != null) {
AppendMultiLine(doc, docText.ToString() + Environment.NewLine, indent);
AppendIndent(doc, indent);
doc.AppendLine("Data and other attributes defined here:");
AppendIndent(doc, indent);
doc.AppendLine();
}
IList<object> names = ((IPythonMembersList)oldClass).GetMemberNames(context);
List sortNames = new List(names);
sortNames.sort(context);
names = sortNames;
foreach (string name in names) {
if (name == "__class__") continue;
object value;
if (oldClass.TryLookupSlot(name, out value))
help(context, doced, doc, indent + 1, value);
}
}
}
private static void AppendMultiLine(StringBuilder doc, string multiline, int indent) {
string[] docs = multiline.Split('\n');
for (int i = 0; i < docs.Length; i++) {
AppendIndent(doc, indent + 1);
doc.Append(docs[i]);
doc.Append('\n');
}
}
private static void AppendIndent(StringBuilder doc, int indent) {
doc.Append(" | ");
for (int i = 0; i < indent; i++) doc.Append(" ");
}
//??? type this to string
public static object hex(object o) {
return PythonOps.Hex(o);
}
public static object id(object o) {
long res = PythonOps.Id(o);
if (PythonOps.Id(o) <= Int32.MaxValue) {
return (int)res;
}
return (BigInteger)res;
}
[LightThrowing]
public static object input(CodeContext/*!*/ context) {
return input(context, null);
}
[LightThrowing]
public static object input(CodeContext/*!*/ context, object prompt) {
return eval(context, raw_input(context, prompt));
}
public static PythonType @int {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(int));
}
}
public static string intern(object o) {
string s = o as string;
if (s == null) {
throw PythonOps.TypeError("intern: argument must be string");
}
return string.Intern(s);
}
public static bool isinstance(object o, [NotNull]PythonType typeinfo) {
return PythonOps.IsInstance(o, typeinfo);
}
public static bool isinstance(CodeContext context, object o, [NotNull]PythonTuple typeinfo) {
return PythonOps.IsInstance(context, o, typeinfo);
}
public static bool isinstance(CodeContext context, object o, object typeinfo) {
return PythonOps.IsInstance(context, o, typeinfo);
}
public static bool issubclass(CodeContext context, [NotNull]OldClass c, object typeinfo) {
return PythonOps.IsSubClass(context, c.TypeObject, typeinfo);
}
public static bool issubclass(CodeContext context, [NotNull]PythonType c, object typeinfo) {
return PythonOps.IsSubClass(context, c, typeinfo);
}
public static bool issubclass(CodeContext context, [NotNull]PythonType c, [NotNull]PythonType typeinfo) {
return PythonOps.IsSubClass(c, typeinfo);
}
[LightThrowing]
public static object issubclass(CodeContext/*!*/ context, object o, object typeinfo) {
PythonTuple pt = typeinfo as PythonTuple;
if (pt != null) {
// Recursively inspect nested tuple(s)
foreach (object subTypeInfo in pt) {
try {
PythonOps.FunctionPushFrame(PythonContext.GetContext(context));