forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuiltin.cs
More file actions
1823 lines (1520 loc) · 73 KB
/
Builtin.cs
File metadata and controls
1823 lines (1520 loc) · 73 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.Scripting;
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;
[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__ = @"Built-in functions, exceptions, and other objects.
Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
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;
}
}
[Documentation("__import__(name, globals, locals, fromlist, level) -> module\n\nImport a module.")]
[LightThrowing]
public static object __import__(CodeContext/*!*/ context, string name, object globals=null, object locals=null, object fromlist=null, int level=0) {
if (fromlist is string || fromlist is Extensible<string>) {
fromlist = new List<object> { fromlist };
}
IList from = fromlist as IList;
PythonContext pc = context.LanguageContext;
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));
}
if (ret is PythonModule mod && 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(CodeContext context, object x) {
IEnumerator i = PythonOps.GetEnumerator(context, x);
while (i.MoveNext()) {
if (!PythonOps.IsTrue(i.Current)) return false;
}
return true;
}
public static bool any(CodeContext context, object x) {
IEnumerator i = PythonOps.GetEnumerator(context, x);
while (i.MoveNext()) {
if (PythonOps.IsTrue(i.Current)) return true;
}
return false;
}
public static string ascii(CodeContext/*!*/ context, object @object) {
return PythonOps.Ascii(context, @object);
}
public static string bin(object obj) {
if (obj is int) return Int32Ops.ToBinary((int)obj);
if (obj is Runtime.Index) return Int32Ops.ToBinary(Converter.ConvertToIndex((Runtime.Index)obj));
if (obj is BigInteger) return BigIntegerOps.ToBinary((BigInteger)obj);
object res = PythonOps.Index(obj);
if (res is int) {
return Int32Ops.ToBinary((int)res);
} else if (res is BigInteger) {
return BigIntegerOps.ToBinary((BigInteger)res);
}
throw PythonOps.TypeError("__index__ returned non-int (type {0})", PythonOps.GetPythonTypeName(res));
}
public static PythonType @bool {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(bool));
}
}
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).")]
public static bool callable(CodeContext/*!*/ context, object o) {
return PythonOps.IsCallable(context, o);
}
[Documentation("chr(i) -> character\n\nReturn a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.")]
[LightThrowing]
public static object chr(int value) {
if (value < 0 || value > 0x10ffff) {
return LightExceptions.Throw(PythonOps.ValueError("chr() arg not in range(0x110000)"));
}
if (value > char.MaxValue) return char.ConvertFromUtf32(value); // not technically correct, but better than truncating
return ScriptingRuntimeHelpers.CharToString((char)value);
}
public static PythonType classmethod {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(classmethod));
}
}
[Documentation("compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\n" +
"Compile a unit of source code.\n\n" +
"The source can be compiled either as exec, eval, or single.\n" +
"exec compiles the code as if it were a file\n" +
"eval compiles the code as if were an expression\n" +
"single compiles a single statement\n\n" +
"source can either be a string, bytes or an AST object")]
public static object compile(CodeContext/*!*/ context, _ast.AST source, string filename, string mode, object flags = null, object dont_inherit = null, int optimize = -1) {
// TODO: implement optimize
ValidateCompileMode(mode);
bool astOnly = flags != null && (Converter.ConvertToInt32(flags) & _ast.PyCF_ONLY_AST) != 0;
if (astOnly) {
return source;
} else {
PythonAst ast = _ast.ConvertToPythonAst(context, (_ast.AST)source, filename);
ast.Bind();
ScriptCode code = ast.ToScriptCode();
return ((RunnableScriptCode)code).GetFunctionCode(true);
}
}
[Documentation("")] // provided by first overload
public static object compile(CodeContext/*!*/ context, [BytesConversion]IList<byte> source, string filename, string mode, object flags = null, object dont_inherit = null, int optimize = -1) {
// TODO: implement optimize
var sourceCodeKind = ValidateCompileMode(mode);
byte[] bytes = source as byte[] ?? ((source is Bytes b) ? b.UnsafeByteArray : source.ToArray());
var contentProvider = new MemoryStreamContentProvider(context.LanguageContext, bytes, filename);
var sourceUnit = context.LanguageContext.CreateSourceUnit(contentProvider, filename, sourceCodeKind);
return CompileHelper(context, sourceUnit, mode, flags, dont_inherit);
}
[Documentation("")] // provided by first overload
public static object compile(CodeContext/*!*/ context, string source, string filename, string mode, object flags = null, object dont_inherit = null, int optimize = -1) {
// TODO: implement optimize
var sourceCodeKind = ValidateCompileMode(mode);
if (source.IndexOf('\0') != -1) {
throw PythonOps.TypeError("compile() expected string without null bytes");
}
var sourceUnit = context.LanguageContext.CreateSnippet(source, filename, sourceCodeKind);
return CompileHelper(context, sourceUnit, mode, flags, dont_inherit);
}
private static SourceCodeKind ValidateCompileMode(string mode) {
switch (mode) {
case "exec": return SourceCodeKind.Statements;
case "eval": return SourceCodeKind.Expression;
case "single": return SourceCodeKind.InteractiveCode;
default:
throw PythonOps.ValueError("compile() arg 3 must be 'exec' or 'eval' or 'single'");
}
}
private static object CompileHelper(CodeContext/*!*/ context, SourceUnit sourceUnit, string mode, object flags, 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;
}
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;
}
return !astOnly ?
(object)FunctionCode.FromSourceUnit(sourceUnit, opts, true) :
(object)_ast.BuildAst(context, sourceUnit, opts, mode);
}
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 PythonList dir(CodeContext/*!*/ context) {
PythonList res = PythonOps.MakeListFromSequence(context.Dict.Keys);
res.sort(context);
return res;
}
public static PythonList dir(CodeContext/*!*/ context, object o) {
IList<object> ret = PythonOps.GetAttrNames(context, o);
PythonList lret = new PythonList(ret);
lret.sort(context);
return lret;
}
public static object divmod(CodeContext/*!*/ context, object x, object y) {
Debug.Assert(NotImplementedType.Value != null);
return context.LanguageContext.DivMod(x, y);
}
public static PythonType enumerate {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(Enumerate));
}
}
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;
}
[Documentation("eval(source[, globals[, locals]]) -> value\n\n" +
"Evaluate the expression in the context of globals and locals.\n" +
"The expression can be either be a string, bytes\n" +
"or a code object returned by compile()")]
[LightThrowing]
public static object eval(CodeContext/*!*/ context, [NotNull]FunctionCode code, PythonDictionary globals = null, object locals = null)
=> code.Call(GetExecEvalScopeOptional(context, globals, locals, copyModule: false));
[Documentation("")] // provided by first overload
[LightThrowing]
public static object eval(CodeContext/*!*/ context, [BytesConversion, NotNull]IList<byte> expression, PythonDictionary globals = null, object locals = null) {
if (locals != null && !PythonOps.IsMappingType(context, locals)) {
throw PythonOps.TypeError("locals must be mapping");
}
byte[] bytes = expression as byte[] ?? ((expression is Bytes b) ? b.UnsafeByteArray : expression.ToArray());
// Count number of whitespace characters to skip at the beginning.
// It assumes an ASCII compatible encoding (like UTF-8 or Latin-1) but excludes UTF-16 or UTF-32.
// This is not a problem as widechar Unicode encodings, to be recognized, must start with a BOM anyway
// Whitespace after a BOM is not skipped (CPython behavior).
int skip = 0;
while (skip < bytes.Length && (bytes[skip] == (byte)' ' || bytes[skip] == (byte)'\t')) skip++;
var sourceUnit = context.LanguageContext.CreateSourceUnit(
new MemoryStreamContentProvider(context.LanguageContext, bytes, skip, bytes.Length - skip, "<string>"),
"<string>",
SourceCodeKind.Expression);
PythonCompilerOptions compilerOptions = GetRuntimeGeneratedCodeCompilerOptions(context, inheritContext: true, cflags: 0);
compilerOptions.Module |= ModuleOptions.LightThrow;
compilerOptions.Module &= ~ModuleOptions.ModuleBuiltins;
var code = FunctionCode.FromSourceUnit(sourceUnit, compilerOptions, register: false);
return eval(context, code, globals, locals);
}
[LightThrowing]
public static object eval(CodeContext/*!*/ context, [NotNull]string expression, PythonDictionary globals = null, object locals = null) {
if (locals != null && !PythonOps.IsMappingType(context, locals)) {
throw PythonOps.TypeError("locals must be mapping");
}
expression = expression.TrimStart(' ', '\t'); // CPython does whitespace trimming, but does not remove BOM
var sourceUnit = context.LanguageContext.CreateSnippet(expression, "<string>", SourceCodeKind.Expression);
var compilerOptions = GetRuntimeGeneratedCodeCompilerOptions(context, inheritContext: true, cflags: 0);
compilerOptions.Module |= ModuleOptions.LightThrow;
compilerOptions.Module &= ~ModuleOptions.ModuleBuiltins;
var code = FunctionCode.FromSourceUnit(sourceUnit, compilerOptions, register: false);
return eval(context, code, globals, locals);
}
[Documentation("exec(object[, globals[, locals]])\n\n" +
"Read and execute code from an object, which can be a string, bytes or a code object.\n" +
"The globals and locals are dictionaries providing the context.")]
public static void exec(CodeContext/*!*/ context, [NotNull]FunctionCode code, PythonDictionary globals = null, object locals = null) {
if (locals == null) locals = globals;
if (globals == null) globals = context.GlobalDict;
if (locals != null && !PythonOps.IsMappingType(context, locals)) {
throw PythonOps.TypeError($"locals must be mapping or None, not {DynamicHelpers.GetPythonType(locals).Name}");
}
CodeContext execContext = Builtin.GetExecEvalScope(context, globals, Builtin.GetAttrLocals(context, locals), true, false);
if (context.LanguageContext.PythonOptions.Frames) {
List<FunctionStack> stack = PythonOps.PushFrame(execContext, code);
try {
code.Call(execContext);
} finally {
stack.RemoveAt(stack.Count - 1);
}
} else {
code.Call(execContext);
}
}
[Documentation("")] // provided by first overload
public static void exec(CodeContext/*!*/ context, [NotNull]string code, PythonDictionary globals = null, object locals = null) {
SourceUnit source = context.LanguageContext.CreateSourceUnit(new NoLineFeedSourceContentProvider(code), "<string>", SourceCodeKind.Statements);
PythonCompilerOptions compilerOptions = Builtin.GetRuntimeGeneratedCodeCompilerOptions(context, true, 0);
var funcCode = FunctionCode.FromSourceUnit(source, compilerOptions, false);
exec(context, funcCode, globals, locals);
}
[Documentation("")] // provided by first overload
public static void exec(CodeContext/*!*/ context, [BytesConversion, NotNull]IList<byte> code, PythonDictionary globals = null, object locals = null) {
byte[] bytes = code as byte[] ?? ((code is Bytes b) ? b.UnsafeByteArray : code.ToArray());
SourceUnit source = context.LanguageContext.CreateSourceUnit(
new MemoryStreamContentProvider(context.LanguageContext, bytes, "<string>"),
"<string>",
SourceCodeKind.Statements);
PythonCompilerOptions compilerOptions = Builtin.GetRuntimeGeneratedCodeCompilerOptions(context, true, 0);
var funcCode = FunctionCode.FromSourceUnit(source, compilerOptions, false);
exec(context, funcCode, globals, locals);
}
public static PythonType filter {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(Filter));
}
}
public static PythonType @float {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(double));
}
}
public static string format(CodeContext/*!*/ context, object argValue, string formatSpec="") {
object res;
// call __format__ with the format spec (__format__ is defined on object, so this always succeeds)
PythonTypeOps.TryInvokeBinaryOperator(
context,
argValue,
formatSpec,
"__format__",
out res);
if (!(res is string strRes)) {
throw PythonOps.TypeError("{0}.__format__ must return string or unicode, not {1}", PythonTypeOps.GetName(argValue), PythonTypeOps.GetName(res));
}
return strRes;
}
public static PythonType frozenset {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(FrozenSetCollection));
}
}
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(context.LanguageContext.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 Int32Ops.__hash__(o);
}
public static int hash(CodeContext/*!*/ context, Extensible<int> o) {
return PythonContext.Hash(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) {
if (doced.Contains(obj)) return; // document things only once
doced.Add(obj);
if (obj is string strVal) {
if (indent != 0) return;
// try and find things that string could refer to,
// then call help on them.
foreach (object module in context.LanguageContext.SystemStateModules.Values) {
IList<object> attrs = PythonOps.GetAttrNames(context, module);
PythonList candidates = new PythonList();
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.
PythonType type = null;
BuiltinFunction builtinFunction = null;
PythonFunction 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 (obj is PythonType type) {
// 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__"));
}
if (type.TryResolveSlot(context, "__doc__", out PythonTypeSlot dts)) {
if (dts.TryGetValue(context, null, type, out object 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();
}
PythonList names = type.GetMemberNames(context);
names.sort(context);
foreach (string name in names) {
if (name == "__class__") continue;
if (type.TryLookupSlot(context, name, out PythonTypeSlot value) &&
value.TryGetValue(context, null, type, out object val)) {
help(context, doced, doc, indent + 1, val);
}
}
} else if (obj is BuiltinMethodDescriptor methodDesc) {
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 (obj is BuiltinFunction builtinFunction) {
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 (obj is PythonFunction function) {
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 (obj is Method method && method.__func__ is PythonFunction func) {
if (indent == 0) doc.AppendFormat("Help on method {0} in module {1}:\n\n", func.__name__, func.__module__);
AppendIndent(doc, indent);
doc.Append(func.GetSignatureString());
doc.AppendFormat(" method of {0} instance\n", PythonOps.ToString(method.im_class));
string pfDoc = Converter.ConvertToString(func.__doc__);
if (!string.IsNullOrEmpty(pfDoc)) {
AppendMultiLine(doc, pfDoc, indent);
}
} else if (obj is PythonModule pyModule) {
foreach (string name in pyModule.__dict__.Keys) {
if (name == "__class__" || name == "__builtins__") continue;
if (pyModule.__dict__.TryGetValue(name, out object 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) {
object res = PythonOps.Index(o);
if (res is BigInteger b) {
if (b < 0) {
return "-0x" + (-b).ToString("x");
} else {
return "0x" + b.ToString("x");
}
}
int x = (int)res;
if (x < 0) {
return "-0x" + Convert.ToString(-x, 16);
} else {
return "0x" + Convert.ToString(x, 16);
}
}
public static object id(object o) {
long res = PythonOps.Id(o);
if (PythonOps.Id(o) <= Int32.MaxValue) {
return (int)res;
}
return (BigInteger)res;
}
public static PythonType @int {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(int));
}
}
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]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) {
if (typeinfo is PythonTuple pt) {
// Recursively inspect nested tuple(s)
foreach (object subTypeInfo in pt) {
try {
PythonOps.FunctionPushFrame(context.LanguageContext);
var res = issubclass(context, o, subTypeInfo);
if (res == ScriptingRuntimeHelpers.True) {
return ScriptingRuntimeHelpers.True;
} else if (LightExceptions.IsLightException(res)) {
return res;
}
} finally {
PythonOps.FunctionPopFrame();
}
}
return ScriptingRuntimeHelpers.False;
}
object bases;
PythonTuple tupleBases;
if (!PythonOps.TryGetBoundAttr(o, "__bases__", out bases) || (tupleBases = bases as PythonTuple) == null) {
return LightExceptions.Throw(PythonOps.TypeError("issubclass() arg 1 must be a class"));
}
if (o == typeinfo) {
return ScriptingRuntimeHelpers.True;
}
foreach (object baseCls in tupleBases) {
PythonType pyType;
if (baseCls == typeinfo) {
return ScriptingRuntimeHelpers.True;
} else if ((pyType = baseCls as PythonType) != null) {
if (issubclass(context, pyType, typeinfo)) {
return ScriptingRuntimeHelpers.True;
}
} else if (hasattr(context, baseCls, "__bases__")) {
var res = issubclass(context, baseCls, typeinfo);
if (res == ScriptingRuntimeHelpers.True) {
return ScriptingRuntimeHelpers.True;
} else if (LightExceptions.IsLightException(res)) {
return res;
}
}
}
return ScriptingRuntimeHelpers.False;
}
public static object iter(CodeContext/*!*/ context, object o) {
return PythonOps.GetEnumeratorObject(context, o);
}
public static object iter(CodeContext/*!*/ context, object func, object sentinel) {
if (!PythonOps.IsCallable(context, func)) {
throw PythonOps.TypeError("iter(v, w): v must be callable");
}
return new SentinelIterator(context, func, sentinel);
}
public static int len([NotNull]string/*!*/ str) {
return str.Length;
}
public static int len([NotNull]ExtensibleString/*!*/ str) {
return str.__len__();
}
public static int len([NotNull]PythonList/*!*/ list) {
return list.__len__();
}
public static int len([NotNull]PythonTuple/*!*/ tuple) {
return tuple.__len__();
}
public static int len([NotNull]PythonDictionary/*!*/ dict) {
return dict.__len__();
}
public static int len([NotNull]ICollection/*!*/ collection) {
return collection.Count;
}
public static int len(object o) {
return PythonOps.Length(o);
}
public static PythonType set {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(SetCollection));
}
}
public static PythonType list {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(PythonList));
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public static object locals(CodeContext/*!*/ context) {
PythonDictionary dict = context.Dict;
if (dict._storage is ObjectAttributesAdapter adapter) {
// we've wrapped Locals in an PythonDictionary, give the user back the
// original object.
return adapter.Backing;
}
return context.Dict;
}
public static PythonType @long {
get {
return TypeCache.BigInteger;
}
}
public static PythonType memoryview {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(MemoryView));
}
}
private static CallSite<Func<CallSite, CodeContext, T, T1, object>> MakeMapSite<T, T1>(CodeContext/*!*/ context) {
return CallSite<Func<CallSite, CodeContext, T, T1, object>>.Create(
context.LanguageContext.InvokeOne
);
}
public static PythonType map {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(Map));
}
}
private static object UndefinedKeywordArgument = new object();
public static object max(CodeContext/*!*/ context, object x) {
IEnumerator i = PythonOps.GetEnumerator(x);
if (!i.MoveNext())
throw PythonOps.ValueError("max() arg is an empty sequence");
object ret = i.Current;
PythonContext pc = context.LanguageContext;
while (i.MoveNext()) {
if (pc.GreaterThan(i.Current, ret)) ret = i.Current;
}
return ret;
}
public static object max(CodeContext/*!*/ context, object x, object y) {
return context.LanguageContext.GreaterThan(x, y) ? x : y;
}
public static object max(CodeContext/*!*/ context, params object[] args) {
if (args.Length > 0) {
object ret = args[0];
if (args.Length == 1) {
return max(context, ret);
}
PythonContext pc = context.LanguageContext;
for (int i = 1; i < args.Length; i++) {
if (pc.GreaterThan(args[i], ret)) {
ret = args[i];
}
}
return ret;
} else {
throw PythonOps.TypeError("max expected 1 arguments, got 0");
}
}
public static object max(CodeContext/*!*/ context, object x, [ParamDictionary]IDictionary<object, object> dict) {
IEnumerator i = PythonOps.GetEnumerator(x);
var kwargTuple = GetMaxKwArg(dict,isDefaultAllowed:true);
object method = kwargTuple.Item1;
object def = kwargTuple.Item2;
if (!i.MoveNext()) {
if (def != UndefinedKeywordArgument) return def;
throw PythonOps.ValueError("max() arg is an empty sequence");
}
if (method == UndefinedKeywordArgument) {
return max(context, x);
}
object ret = i.Current;
object retValue = PythonCalls.Call(context, method, i.Current);
PythonContext pc = context.LanguageContext;
while (i.MoveNext()) {
object tmpRetValue = PythonCalls.Call(context, method, i.Current);
if (pc.GreaterThan(tmpRetValue, retValue)) {
ret = i.Current;
retValue = tmpRetValue;
}
}
return ret;
}
public static object max(CodeContext/*!*/ context, object x, object y, [ParamDictionary] IDictionary<object, object> dict) {
var kwargTuple = GetMaxKwArg(dict, isDefaultAllowed: false);
object method = kwargTuple.Item1;
PythonContext pc = context.LanguageContext;
return pc.GreaterThan(PythonCalls.Call(context, method, x), PythonCalls.Call(context, method, y)) ? x : y;
}
public static object max(CodeContext/*!*/ context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) {
var kwargTuple = GetMaxKwArg(dict, isDefaultAllowed: false);
object method = kwargTuple.Item1;
if (args.Length > 0) {
int retIndex = 0;
if (args.Length == 1) {
return max(context, args[retIndex], dict);
}
object retValue = PythonCalls.Call(context, method, args[retIndex]);
PythonContext pc = context.LanguageContext;
for (int i = 1; i < args.Length; i++) {
object tmpRetValue = PythonCalls.Call(context, method, args[i]);
if (pc.GreaterThan(tmpRetValue, retValue)) {
retIndex = i;
retValue = tmpRetValue;
}
}
return args[retIndex];
} else {
throw PythonOps.TypeError("max expected 1 arguments, got 0");
}
}
private static Tuple<object, object> GetMaxKwArg(IDictionary<object, object> dict, bool isDefaultAllowed) {
if (dict.Count != 1 && dict.Count != 2)
throw PythonOps.TypeError("max() should have only 2 keyword arguments, but got {0} keyword arguments", dict.Count);
if (dict.Keys.Contains("default") && !isDefaultAllowed) {
throw PythonOps.TypeError("Cannot specify a default for max() with multiple positional arguments");
}
return VerifyKeys("max", dict);
}
public static object min(CodeContext/*!*/ context, object x) {
IEnumerator i = PythonOps.GetEnumerator(x);
if (!i.MoveNext()) {
throw PythonOps.ValueError("empty sequence");
}
object ret = i.Current;
PythonContext pc = context.LanguageContext;
while (i.MoveNext()) {
if (pc.LessThan(i.Current, ret)) ret = i.Current;
}
return ret;
}
public static object min(CodeContext/*!*/ context, object x, object y) {
return context.LanguageContext.LessThan(x, y) ? x : y;
}
public static object min(CodeContext/*!*/ context, params object[] args) {
if (args.Length > 0) {
object ret = args[0];