Source

pypy / pypy / translator / cli / src / pypylib.cs

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
using System;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using pypy.runtime;

namespace pypy.test
{
    public class Result 
    {
        public static string ToPython(int x)    { return x.ToString(); }
        public static string ToPython(bool x)   { return x.ToString(); }
        public static string ToPython(double x) { return string.Format("{0:F8}", x); }
        public static string ToPython(char x)   { return string.Format("'{0}'", x);  }
        public static string ToPython(uint x)   { return x.ToString(); }
        public static string ToPython(long x)   { return x.ToString(); }
        public static string ToPython(ulong x)  { return x.ToString(); }
        public static string ToPython(short x)  { return x.ToString(); }
        // XXX: it does not support strings containing "'".
        public static string ToPython(string x) { 
            if (x == null)
                return "None";
            else {
                string res = "";
                foreach(char ch in x)
                    if (ch >= 32 && ch < 128)
                        res+= ch;
                    else
                        res+= string.Format("\\x{0:X2}", (int)ch);
                return string.Format("'{0}'", res);
            }
        }

        public static string ToPython_unicode(string x) { return "u" + ToPython(x); }
        public static string ToPython_unicode(char x)   { return "u" + ToPython(x); }

        public static string ToPython(object x) {
            if (x == null)
                return "None";
            else if (x is Array)
                return ArrayToPython((Array)x);
            else
                return x.ToString();
        }

        private static string ArrayToPython(Array array)
        {
            string res = "[";
            foreach(object item in array) {
                if (item != null && item.GetType() == typeof(string)) {
                    object tmp = (object)item;
                    res += ToPython((string)tmp) + ",";
                }
                else if (item.GetType() == typeof(char)) {
                    object tmp = (object)item;
                    res += pypy.test.Result.ToPython((char)tmp) + ",";
                } 
                else
                    res += ToPython(item) + ",";
                
            }
            res += "]";
            return res;
        }

        public static string InstanceToPython(object obj) 
        { 
            return string.Format("InstanceWrapper('{0}')", obj.GetType().FullName);
        }

        public static string FormatException(object obj) 
        { 
            return string.Format("ExceptionWrapper('{0}')", obj.GetType().FullName);
        }
    }

    public class Convert {
        public static double ToDouble(string s)
        {
            if (s == "inf")
                return Double.PositiveInfinity;
            else if (s == "-inf")
                return Double.NegativeInfinity;
            else if (s == "nan")
                return Double.NaN;
            else {
                System.Globalization.NumberFormatInfo formatter;
                formatter = new System.Globalization.NumberFormatInfo();
                formatter.NumberDecimalSeparator = ".";
                return System.Convert.ToDouble(s, formatter);
            }
        }
    }

    public delegate double DelegateType_int__0();
    public delegate double DelegateType_double__double_1(double a);
    public delegate double DelegateType_double_int_double(int a, double b);
    public delegate void DelegateType_void_int_1(int a);
    public delegate bool DelegateType_bool_bool_1(bool a);
    public delegate char DelegateType_char_char_1(char a);
    public delegate int DelegateType_int__int_1(int a);
    public delegate int DelegateType_int__int_2(int a, int b);
    public delegate int DelegateType_int__int_3(int a, int b, int c);
    public delegate int DelegateType_int__int_5(int a, int b, int c, int d, int e);
    public delegate int DelegateType_int__int_27(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25, int a26);
    public delegate int DelegateType_int__int_100(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25, int a26, int a27, int a28, int a29, int a30, int a31, int a32, int a33, int a34, int a35, int a36, int a37, int a38, int a39, int a40, int a41, int a42, int a43, int a44, int a45, int a46, int a47, int a48, int a49, int a50, int a51, int a52, int a53, int a54, int a55, int a56, int a57, int a58, int a59, int a60, int a61, int a62, int a63, int a64, int a65, int a66, int a67, int a68, int a69, int a70, int a71, int a72, int a73, int a74, int a75, int a76, int a77, int a78, int a79, int a80, int a81, int a82, int a83, int a84, int a85, int a86, int a87, int a88, int a89, int a90, int a91, int a92, int a93, int a94, int a95, int a96, int a97, int a98, int a99);

    public class DummyClass {
        public static object myfield;
    }

}

namespace pypy.runtime
{

    public delegate void LoopDelegate(InputArgs args);

    public class InputArgs {
      public int[] ints = new int[256];
      public double[] floats = new double[256];
      public object[] objs = new object[256];
      public object exc_value = null;
      public int failed_op = -1;

      public int get_int(int i)
      {
        return ints[i];
      }

      public void set_int(int i, int n)
      {
        ints[i] = n;
      }

      public double get_float(int i)
      {
        return floats[i];
      }

      public void set_float(int i, double n)
      {
        floats[i] = n;
      }

      public object get_obj(int i)
      {
        return objs[i];
      }

      public void set_obj(int i, object o)
      {
        objs[i] = o;
      }

      public object get_exc_value()
      {
        return exc_value;
      }

      public void set_exc_value(object v)
      {
        exc_value = v;
      }

      public int get_failed_op()
      {
        return failed_op;
      }

      public void ensure_ints(int n)
      {
        if (ints.Length < n)
          ints = new int[n];
      }

      public void ensure_floats(int n)
      {
        if (floats.Length < n)
          floats = new double[n];
      }

      public void ensure_objs(int n)
      {
        if (objs.Length < n)
          objs = new object[n];

      }
    }

  /*
    public delegate uint FlexSwitchCase(uint block, InputArgs args);

    // XXX: there is a lot of code duplication between the next three classes,
    // but it's hard to share the code in a way that it's both efficient and
    // supported by gencli
    public class MethodIdMap
    { 
      public FlexSwitchCase[] cases = new FlexSwitchCase[4];

      public void add_case(int method_id, FlexSwitchCase c)
      {
        if (cases.Length <= method_id)
          grow();
        cases[method_id] = c;
      }

      public uint jumpto(uint blockid, InputArgs args)
      {
        uint method_id = (blockid & 0xFFFF0000) >> 16;
        return cases[method_id](blockid, args);
      }

      private void grow()
      {
        int newsize = cases.Length * 2;
        FlexSwitchCase[] newcases = new FlexSwitchCase[newsize];
        Array.Copy(cases, newcases, cases.Length);
        cases = newcases;
      }
    }

    public class BaseLowLevelFlexSwitch
    {
        public uint default_blockid = 0xFFFFFFFF;
        public void set_default_blockid(uint blockid)
        {
            this.default_blockid = blockid;
        }
    }

    public class IntLowLevelFlexSwitch: BaseLowLevelFlexSwitch
    {
        public int numcases = 0;
        public int[] values = new int[4];
        public FlexSwitchCase[] cases = new FlexSwitchCase[4];

        public void add_case(int value, FlexSwitchCase c)
        {
            if (numcases >= values.Length)
                grow();
            values[numcases] = value;
            cases[numcases] = c;
            numcases++;
        }

        private void grow()
        {
            int newsize = values.Length * 2;
            int[] newvalues = new int[newsize];
            Array.Copy(values, newvalues, values.Length);
            values = newvalues;
            
            FlexSwitchCase[] newcases = new FlexSwitchCase[newsize];
            Array.Copy(cases, newcases, cases.Length);
            cases = newcases;
        }
        
        public uint execute(int value, InputArgs args)
        {
            for(int i=0; i<numcases; i++)
              if (values[i] == value) {
                  // 0 stands for "the first block of the function", see the comment
                  // in rgenop.FlexCaseMethod.emit_preamble
                  return cases[i](0, args); 
                }
            return default_blockid;
        }
    }

    public class ObjectLowLevelFlexSwitch: BaseLowLevelFlexSwitch
    {
        public int numcases = 0;
        public object[] values = new object[4];
        public FlexSwitchCase[] cases = new FlexSwitchCase[4];

        public void add_case(object value, FlexSwitchCase c)
        {
            if (numcases >= values.Length)
                grow();
            values[numcases] = value;
            cases[numcases] = c;
            numcases++;
        }

        private void grow()
        {
            int newsize = values.Length * 2;
            object[] newvalues = new object[newsize];
            Array.Copy(values, newvalues, values.Length);
            values = newvalues;
            
            FlexSwitchCase[] newcases = new FlexSwitchCase[newsize];
            Array.Copy(cases, newcases, cases.Length);
            cases = newcases;
        }
        
        public uint execute(object value, InputArgs args)
        {
            for(int i=0; i<numcases; i++)
              if (values[i] == value) {
                  // 0 stands for "the first block of the function", see the comment
                  // in rgenop.FlexCaseMethod.emit_preamble
                  return cases[i](0, args); 
                }
            return default_blockid;
        }
    }
  */
        
    public class DelegateHolder
    {
        public LoopDelegate func;

        // we need getter and setter because we can't directly access fields from RPython
        public void SetFunc(LoopDelegate func)
        {
            this.func = func;
        }

        public LoopDelegate GetFunc()
        {
            return this.func;
        }
    }



    public class AutoSaveAssembly
    {
        private AssemblyBuilder assembly;
        private bool saved = false;
        private string name;

        public static AutoSaveAssembly Create(string name)
        {
            return new AutoSaveAssembly(name);
        }

        public AutoSaveAssembly(string name)
        {
            this.name = name;
            AssemblyName assemblyName = new AssemblyName(); 
            assemblyName.Name = name;
            this.assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
        }

        public void Save()
        {
            if (this.saved)
                return;
            this.assembly.Save(this.name);
            this.saved = true;
        }

        ~AutoSaveAssembly()
        {
            this.Save();
        }

        public AssemblyBuilder GetAssemblyBuilder()
        {
            return this.assembly;
        }

        public static TypeBuilder DefineType(ModuleBuilder module, string name)
        {
            return module.DefineType(name,
                                     TypeAttributes.Public |
                                     TypeAttributes.Class);
        }

        public static MethodBuilder DefineMethod(TypeBuilder typeBuilder, string name, Type res, Type[] args)
        {
            return typeBuilder.DefineMethod("invoke",
                                            MethodAttributes.HideBySig | 
                                            MethodAttributes.Static | 
                                            MethodAttributes.Public, 
                                            res, 
                                            args);
        }

        
    }

    public class Utils
    {

        public static DynamicMethod CreateDynamicMethod(string name, Type res, Type[] args)
        {
            return new DynamicMethod(name, res, args, typeof(Utils).Module);
        }

        // if you call il.Emit(OpCodes.Ldc_R8, mydouble) from pythonnet, it
        // selects the wrong overload. To work around it, we call it from C# and
        // live happy
        public static void Emit_Ldc_R8(ILGenerator il, double val) 
        {
            il.Emit(OpCodes.Ldc_R8, val);
        }

        public static object RuntimeNew(Type t)
        {
            return t.GetConstructor(new Type[0]).Invoke(new object[0]);
        }

        public static bool SubclassOf(Type a, Type b)
        {
            return (a == b || a.IsSubclassOf(b));
        }

        public static string OOString(int n, int base_)
        {
            if (base_ == -1)
                base_ = 10;
            if (n<0 && base_ != 10)
                return "-" + Convert.ToString(-n, base_);
            else
                return Convert.ToString(n, base_);
        }

        public static string OOString(uint n, int base_)
        {
            if (base_ == -1)
                base_ = 10;
            return Convert.ToString(n, base_);
        }

        public static string OOString(long n, int base_)
        {
            if (base_ == -1)
                base_ = 10;
            if (n<0 && base_ != 10)
                return "-" + Convert.ToString(-n, base_);
            else
                return Convert.ToString(n, base_);
        }

        public static string OOString(double d, int base_)
        {
            return d.ToString();
        }

        public static string OOString(object obj, int base_)
        {
          if (obj == null)
            return "<null object>";
          else
            return string.Format("<{0} object>", obj.GetType().FullName);
        }

        public static string OOString(char ch, int base_)
        {
            return ch.ToString();
        }

        public static string OOString(string s, int base_)
        {
            return s;
        }

        public static string OOString(bool b, int base_)
        {
            return b.ToString();
        }

        private static void check_ascii(char ch)
        {
            if ((int)ch > 127)
                Helpers.raise_UnicodeDecodeError();
        }

        public static string OOUnicode(char ch)
        {
            return ch.ToString();
        }

        public static string OOUnicode(string s)
        {
            foreach(char ch in s)
                check_ascii(ch);
            return s;
        }

        public static int OOParseInt(string s, int base_)
        {
            return Convert.ToInt32(s, base_);
        }

        public static double OOParseFloat(string s)
        {
            try {
                return Double.Parse(s.Trim());
            }
            catch(FormatException e) {
                Helpers.raise_ValueError();
                return -1;
            }
        }

        public static bool Equal<T>(T t1, T t2) 
        { 
            if (t1 == null)
              return (t2 == null);
            else
              return t1.Equals(t2);
        }

        public static int GetHashCode<T>(T obj)
        {
            if (obj == null)
              return 0;
            else
              return obj.GetHashCode();
        }

        public static void throwInvalidBlockId(uint blockid)
        {
            uint method_id = (blockid & 0xFFFF0000) >> 16;
            uint block_num = (blockid & 0x0000FFFF);
            string msg = string.Format("Invalid block id: 0x{0:X} ({1}, {2})", 
                                       blockid, method_id, block_num);
            throw new Exception(msg);
        }

        public static void Serialize(object obj, string filename)
        {
            FileStream fs = new FileStream(filename, FileMode.Create);
            BinaryFormatter formatter = new BinaryFormatter();
            try {
                formatter.Serialize(fs, obj);
            }
            catch (SerializationException e) {
                Console.Error.WriteLine("Failed to serialize. Reason: " + e.Message);
                throw;
            }
            finally {
                fs.Close();
            }
        }

        public static object Deserialize(string filename)
        {
            FileStream fs = null;
            try {
                fs = new FileStream(filename, FileMode.Open);
                BinaryFormatter formatter = new BinaryFormatter();
                return formatter.Deserialize(fs);
            }
            catch (FileNotFoundException e) {
                return null;
            }
            catch (SerializationException e) {
                Console.Error.WriteLine("Failed to deserialize. Reason: " + e.Message);
                return null;
            }
            finally {
                if (fs != null)
                    fs.Close();
            }
        }
    }

    public class StringBuilder
    {
        System.Text.StringBuilder builder = new System.Text.StringBuilder();

        public void ll_allocate(int size) { builder.Capacity = size; }
        public void ll_append_char(char ch) { builder.Append(ch); }
        public void ll_append(string s) { builder.Append(s); }
        public string ll_build() { return builder.ToString(); }
    }

    public class String
    {
        public static int ll_hash(string s)
        {
            return s.GetHashCode();
        }
        public static char ll_stritem_nonneg(string s, int index)
        {
            return s[index];
        }

        public static int ll_strlen(string s)
        {
            return s.Length;
        }

        public static string ll_strconcat(string s1, string s2)
        {
            return s1+s2;
        }

        public static bool ll_streq(string s1, string s2)
        {
            return s1 == s2;
        }

        public static int ll_strcmp(string s1, string s2)
        {
            return string.Compare(s1, s2, StringComparison.Ordinal);
        }

        public static bool ll_startswith(string s1, string s2)
        {
            return s1.StartsWith(s2);
        }

        public static bool ll_endswith(string s1, string s2)
        {
            return s1.EndsWith(s2);
        }
        
        public static int ll_find(string s1, string s2, int start, int stop)
        {
            if (stop > s1.Length)
                stop = s1.Length;
            int count = stop-start;
            if (start > s1.Length)
                return -1;
            return s1.IndexOf(s2, start, count);
        }

        public static int ll_count(string s1, string s2, int start, int stop)
        {
            if (stop > s1.Length)
                stop = s1.Length;
            if (s2.Length == 0)
            {
                if ((stop-start) < 0)
                {
                    return 0;
                }
                return stop - start + 1;
            }
            int result = 0;
            int i = start;
            while (true)
            {
                int pos = ll_find(s1, s2, i, stop);
                if (pos < 0)
                    return result;
                result += 1;
                i = pos + s2.Length;
            }
        }

        public static int ll_count_char(string s1, char c, int start, int stop)
        {
            if (stop > s1.Length)
                stop = s1.Length;
            int result = 0;
            for (int i=start; i < stop; i++) {
                if (s1[i] == c)
                    result += 1;
            }
            return result;
        }


        public static int ll_rfind(string s1, string s2, int start, int stop)
        {
            if (stop > s1.Length)
                stop = s1.Length;
            int count = stop-start;
            if (start > s1.Length)
                return -1;
            if (s2 == "")
              return stop;
            return s1.LastIndexOf(s2, stop-1, count);
        }

        public static int ll_find_char(string s, char ch, int start, int stop)
        {
            if (stop > s.Length)
                stop = s.Length;
            int count = stop-start;
            return s.IndexOf(ch, start, count);
        }

        public static int ll_rfind_char(string s, char ch, int start, int stop)
        {
            if (stop > s.Length)
                stop = s.Length;
            int count=stop-start;
            if (start > s.Length || stop == 0)
                return -1;
            return s.LastIndexOf(ch, stop-1, count);
        }

        public static string ll_strip(string s, char ch, bool left, bool right)
        {
            if (left && right)
                return s.Trim(ch);
            else if (left)
                return s.TrimStart(ch);
            else if (right)
                return s.TrimEnd(ch);
            else
                return s;

        }

        public static string ll_upper(string s)
        {
            return s.ToUpper();
        }

        public static string ll_lower(string s)
        {
            return s.ToLower();
        }

        public static string ll_substring(string s, int start, int count)
        {
            return s.Substring(start, count);
        }

        public static string[] ll_split_chr(string s, char ch, int max)
        {
            if (max < 0)
                return s.Split(ch);
            else
                return s.Split(new Char[] {ch}, max + 1);
        }

        public static string[] ll_rsplit_chr(string s, char ch, int max)
        {
            string[] splits = s.Split(ch);
            if (max < 0 || splits.Length <= max + 1)
                return splits;
            else {
                /* XXX not very efficient */
                string first = splits[0];
                // join the first (length - max - 1) items
                int i;
                for (i = 1; i < splits.Length - max; i++)
                    first += ch + splits[i];
                splits[0] = first;
                Array.Copy(splits, i, splits, 1, max);
                Array.Resize(ref splits, max + 1);
                return splits;
            }
        }

        public static bool ll_contains(string s, char ch)
        {
            return s.IndexOf(ch) != -1;
        }

        public static string ll_replace_chr_chr(string s, char ch1, char ch2)
        {
            return s.Replace(ch1, ch2);
        }
    }

    //The public interface List must implement is defined in
    // rpython.ootypesystem.ootype.List.GENERIC_METHODS
    public class List<T>: System.Collections.Generic.List<T>
    {
        public List(): base()
        {
        }

        public List(T[] array): base(array)
        {
        }

        public List(int capacity): base(capacity)
        {
        }

        public override string ToString()
        {
            // TODO: use StringBuilder instead
            string res = "[";
            foreach(T item in this) {
                if (item.GetType() == typeof(string)) {
                    object tmp = (object)item;
                    res += pypy.test.Result.ToPython((string)tmp) + ",";
                }
                else if (item.GetType() == typeof(char)) {
                    object tmp = (object)item;
                    res += pypy.test.Result.ToPython((char)tmp) + ",";
                }                  
                else
                    res += pypy.test.Result.ToPython(item) + ",";
            }
            res += "]";
            return res;
        }

        public int ll_length()
        {
            return this.Count;
        }

        public T ll_getitem_fast(int index)
        {
            return this[index];
        }

        public void ll_setitem_fast(int index, T item)
        {
            this[index] = item;
        }

        public void _ll_resize(int length)
        {
            if (length > this.Count)
                this._ll_resize_ge(length);
            else if (length < this.Count)
                this._ll_resize_le(length);
        }

        public void _ll_resize_ge(int length)
        {
            if (this.Count < length) 
            {
                // TODO: this is inefficient because it can triggers
                // many array resize
                int diff = length - this.Count;
                for(int i=0; i<diff; i++)
                    this.Add(default(T));
            }
        }

        public void _ll_resize_le(int length)
        {
            if (length < this.Count)
            {
                int diff = this.Count - length;
                this.RemoveRange(length, diff);
            }
        }
    }

    public class ListOfVoid
    {
        int Count = 0;

        public ListOfVoid() { }
        public ListOfVoid(int capacity) { }

        public override string ToString()
        {
            // TODO: use StringBuilder instead
            string res = "[";
            for(int i=0; i<this.Count; i++)
                res += "None, ";
            res += "]";
            return res;
        }

        public int ll_length() { return this.Count; }
        public void ll_getitem_fast(int index) { }
        public void ll_setitem_fast(int index) { }
        public void _ll_resize(int length) { this.Count = length; }
        public void _ll_resize_ge(int length) { this.Count = length; }
        public void _ll_resize_le(int length) { this.Count = length; }
    }

    public class Dict<TKey, TValue>: System.Collections.Generic.Dictionary<TKey, TValue>
    {
        IEqualityComparer<TKey> comparer = null;
        TValue cache;

        public Dict() {}
        public Dict(IEqualityComparer<TKey> comparer): base(comparer) 
        { 
            this.comparer = comparer;
        }

        public int ll_length() { return this.Count; }
        public TValue ll_get(TKey key) { return cache; }
        public void ll_set(TKey key, TValue value) { this[key] = value; }
        public bool ll_remove(TKey key) { return this.Remove(key); }
        public bool ll_contains(TKey key) { return this.TryGetValue(key, out cache); }
        public void ll_clear() { this.Clear(); }

        public DictItemsIterator<TKey, TValue> ll_get_items_iterator()
        {
            return new DictItemsIterator<TKey, TValue>(this);
        }

        // XXX: this is CustomDict specific, maybe we should have a separate class for it
        public Dict<TKey, TValue> ll_copy()
        {
            Dict<TKey, TValue> res = new Dict<TKey, TValue>(comparer);
            foreach(KeyValuePair<TKey, TValue> item in this)
                res[item.Key] = item.Value;
            return res;
        }
    }

    // it assumes TValue is a placeholder, it's not really used
    public class DictOfVoid<TKey, TValue>: System.Collections.Generic.Dictionary<TKey, TValue>
    {
        IEqualityComparer<TKey> comparer = null;

        public DictOfVoid() {}
        public DictOfVoid(IEqualityComparer<TKey> comparer): base(comparer)
        {
            this.comparer = comparer;
        }

        public int ll_length() { return this.Count; }
        public void ll_get(TKey key) { }
        public void ll_set(TKey key) { this[key] = default(TValue); }
        public bool ll_remove(TKey key) { return this.Remove(key); }
        public bool ll_contains(TKey key) { return this.ContainsKey(key); }
        public void ll_contains_get() { }
        public void ll_clear() { this.Clear(); }

        public DictItemsIterator<TKey, TValue> ll_get_items_iterator()
        {
            return new DictItemsIterator<TKey, TValue>(this);
        }

        public DictOfVoid<TKey, TValue> ll_copy() // XXX: why it should return a Dict?
        {
            DictOfVoid<TKey, TValue> res = new DictOfVoid<TKey, TValue>(comparer);
            foreach(KeyValuePair<TKey, TValue> item in this)
                res[item.Key] = item.Value;
            return res;            
        }
    }

    // it assumes TKey is a placeholder, it's not really used
    public class DictOfVoidKey<TKey, TValue>
    {
        private int length = 0;
        private TValue elem = default(TValue);

        public DictOfVoidKey() {}
        public DictOfVoidKey(IEqualityComparer<TKey> comparer) {}

        public int ll_length() { return this.length; }
        public TValue ll_get() { return this.elem; }
        
        public void ll_set(TValue value) { 
            this.length = 1;
            this.elem = value;
        }

        public bool ll_remove() {
            if (this.length > 0) {
                this.length = 0;
                return true;
            }
            return false;
        }

        public bool ll_contains() { return (this.length > 0); }
        public void ll_contains_get() { }
        public void ll_clear() { this.length = 0; }

        public DictItemsIterator<TKey, TValue> ll_get_items_iterator()
        {
            Dictionary<TKey, TValue> foo = new Dictionary<TKey, TValue>();
            if (length == 1)
                foo[default(TKey)] = this.elem;
            return new DictItemsIterator<TKey, TValue>(foo);
        }
    }

    public class DictVoidVoid
    {
        private int length = 0;

        public int ll_length() { return length; }
        public void ll_get() { }
        public void ll_set() { length = 1; }
        public bool ll_remove() { 
            if (length == 0)
                return false;
            length = 0;
            return true;
        }
        public bool ll_contains() { return length != 0; }
        public void ll_contains_get() { }
        public void ll_clear() { length = 0; }

        public DictItemsIterator<int, int> ll_get_items_iterator()
        {
            Dictionary<int, int> foo = new Dictionary<int, int>();
            if (length == 1)
                foo[0] = 0;
            return new DictItemsIterator<int, int>(foo);
        }
    }

    public class DictItemsIterator<TKey, TValue>
    {
        Dictionary<TKey, TValue> dict;
        int size;
        TKey[] keys;
        int pos;

        public DictItemsIterator(Dictionary<TKey, TValue> dict)
        {
            this.dict = dict;
            this.size = dict.Count;
            this.keys = new TKey[this.size];
            dict.Keys.CopyTo(this.keys, 0);
            this.pos = -1;
        }

        public bool ll_go_next() { 
            if (this.size != this.dict.Count)
                Helpers.raise_RuntimeError();
            if (this.pos >= this.size-1)
                return false;
            pos++;
            return true;
        }

        public TKey ll_current_key() { 
            return this.keys[this.pos]; 
        }

        public TValue ll_current_value() { 
            TKey key = this.ll_current_key();
            return this.dict[key];
        }
    }

    public class WeakReference
    {
        System.WeakReference wref;

        public void ll_set(object obj)
        {
            this.wref = new System.WeakReference(obj);
        }

        public object ll_deref()
        {
            return this.wref.Target;
        }
    }

    public class Record_Signed_Signed {
        public int item0;
        public int item1;
        public override string ToString() { return string.Format("({0}, {1},)", item0, item1); }
        public override bool Equals(object obj)
        {
            Record_Signed_Signed x = (Record_Signed_Signed)obj;
            return item0 == x.item0 && item1 == x.item1;
        }
        public override int GetHashCode() { return item0.GetHashCode(); }
    }    

    public class Record_Float_Signed {
        public double item0;
        public int item1;
        public override string ToString() { return string.Format("({0}, {1},)", item0, item1); }
        public override bool Equals(object obj)
        {
            Record_Float_Signed x = (Record_Float_Signed)obj;
            return item0 == x.item0 && item1 == x.item1;
        }
        public override int GetHashCode() { return item0.GetHashCode(); }
    }

    public class Record_Float_Float {
        public double item0;
        public double item1;
        public override string ToString() { return string.Format("({0}, {1},)", item0, item1); }
        public override bool Equals(object obj)
        {
            Record_Float_Float x = (Record_Float_Float)obj;
            return item0 == x.item0 && item1 == x.item1;
        }
        public override int GetHashCode() { return item0.GetHashCode(); }
    }

    public class Record_String_String {
        public string item0;
        public string item1;
        public override string ToString() { return string.Format("({0}, {1},)", item0, item1); }
        public override bool Equals(object obj)
        {
            Record_String_String x = (Record_String_String)obj;
            return item0 == x.item0 && item1 == x.item1;
        }
        public override int GetHashCode() { return item0.GetHashCode(); }
    }

    public class Record_Stat_Result {
        public int item0, item3, item4, item5;
        public long item1, item2, item6;
        public double item7, item8, item9;
        public override string ToString() 
        { 
            return string.Format("({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9},)", 
                                 item0, item1, item2, item3, item4, 
                                 item5, item6, item7, item8, item9);
        }
        public override bool Equals(object obj)
        {
            Record_Stat_Result x = (Record_Stat_Result)obj;
            return item0 == x.item0 && item1 == x.item1 && item2 == x.item2 
                && item3 == x.item3 && item4 == x.item4 && item5 == x.item5
                && item6 == x.item6 && item7 == x.item7 && item8 == x.item8
                && item9 == x.item9;
        }
        public override int GetHashCode() { return item0.GetHashCode(); }
    }
}

namespace pypy.builtin
{
    public class ll_strtod
    {
        public static string ll_strtod_formatd(string format, double d)
        {
            // XXX: this is really a quick hack to make things work.
            // it should disappear, because this function is not
            // supported by ootypesystem.
            return d.ToString(); // XXX: we are ignoring "format"
        }
    }

    public class ll_time
    {
        public static double ll_time_time()
        {
            TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
            return t.TotalSeconds;
        }

        public static double ll_time_clock()
        {
          return DateTime.UtcNow.Ticks * 1e-7;
        }

        public static void ll_time_sleep(double seconds)
        {
            System.Threading.Thread.Sleep((int)(seconds*1000));
        }
    }

    public class rffi
    {
        public static int tolower(int chr)
        {
            return (int)Char.ToLower((char)chr);
        }

        public static int locale_tolower(int chr)
        {
            return (int)Char.ToLower((char)chr);
        }

        public static int locale_isupper(int chr)
        {
            return Convert.ToInt32(Char.IsUpper((char)chr));
        }

        public static int locale_islower(int chr)
        {
            return Convert.ToInt32(Char.IsLower((char)chr));
        }

        public static int locale_isalpha(int chr)
        {
            return Convert.ToInt32(Char.IsLetter((char)chr));
        }

        public static int locale_isalnum(int chr)
        {
            return Convert.ToInt32(Char.IsLetterOrDigit((char)chr));
        }

    }

}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.