Source

pypy / pypy / module / micronumpy / types.py

   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
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
import functools
import math

from pypy.interpreter.error import OperationError
from pypy.module.micronumpy import interp_boxes
from pypy.module.micronumpy.arrayimpl.voidbox import VoidBoxStorage
from pypy.objspace.std.floatobject import float2string
from pypy.objspace.std.complexobject import str_format
from rpython.rlib import rfloat, clibffi, rcomplex
from rpython.rlib.rawstorage import (alloc_raw_storage, raw_storage_setitem,
                                  raw_storage_getitem)
from rpython.rlib.objectmodel import specialize
from rpython.rlib.rarithmetic import widen, byteswap, r_ulonglong
from rpython.rtyper.lltypesystem import lltype, rffi
from rpython.rlib.rstruct.runpack import runpack
from rpython.rlib.rstruct.nativefmttable import native_is_bigendian
from rpython.rlib.rstruct.ieee import (float_pack, float_unpack, unpack_float,
                                       pack_float80, unpack_float80)
from rpython.tool.sourcetools import func_with_new_name
from rpython.rlib import jit
from rpython.rlib.rstring import StringBuilder

degToRad = math.pi / 180.0
log2 = math.log(2)
log2e = 1. / log2

def isfinite(d):
    return not rfloat.isinf(d) and not rfloat.isnan(d)

def simple_unary_op(func):
    specialize.argtype(1)(func)
    @functools.wraps(func)
    def dispatcher(self, v):
        raw = self.unbox(v)
        return self.box(
            func(
                self,
                self.for_computation(raw)
            )
        )
    return dispatcher

def complex_unary_op(func):
    specialize.argtype(1)(func)
    @functools.wraps(func)
    def dispatcher(self, v):
        return self.box_complex(
            *func(
                self,
                self.for_computation(self.unbox(v))
            )
        )
    return dispatcher

def complex_to_real_unary_op(func):
    specialize.argtype(1)(func)
    @functools.wraps(func)
    def dispatcher(self, v):
        from pypy.module.micronumpy.interp_boxes import W_GenericBox
        assert isinstance(v, W_GenericBox)
        return self.box_component(
            func(
                self,
                self.for_computation(self.unbox(v))
            )
        )
    return dispatcher


def raw_unary_op(func):
    specialize.argtype(1)(func)
    @functools.wraps(func)
    def dispatcher(self, v):
        return func(
            self,
            self.for_computation(self.unbox(v))
        )
    return dispatcher

def simple_binary_op(func):
    specialize.argtype(1, 2)(func)
    @functools.wraps(func)
    def dispatcher(self, v1, v2):
        return self.box(
            func(
                self,
                self.for_computation(self.unbox(v1)),
                self.for_computation(self.unbox(v2)),
            )
        )
    return dispatcher

def complex_binary_op(func):
    specialize.argtype(1, 2)(func)
    @functools.wraps(func)
    def dispatcher(self, v1, v2):
        return self.box_complex(
            *func(
                self,
                self.for_computation(self.unbox(v1)),
                self.for_computation(self.unbox(v2)),
            )
        )
    return dispatcher

def raw_binary_op(func):
    specialize.argtype(1, 2)(func)
    @functools.wraps(func)
    def dispatcher(self, v1, v2):
        return func(self,
            self.for_computation(self.unbox(v1)),
            self.for_computation(self.unbox(v2))
        )
    return dispatcher

class BaseType(object):
    _attrs_ = ()

    SortRepr = None # placeholders for sorting classes, overloaded in sort.py
    Sort = None

    def _unimplemented_ufunc(self, *args):
        raise NotImplementedError

    def malloc(self, size):
        return alloc_raw_storage(size, track_allocation=False, zero=True)

    def __repr__(self):
        return self.__class__.__name__

class Primitive(object):
    _mixin_ = True

    def get_element_size(self):
        return rffi.sizeof(self.T)

    @specialize.argtype(1)
    def box(self, value):
        return self.BoxType(rffi.cast(self.T, value))

    @specialize.argtype(1, 2)
    def box_complex(self, real, imag):
        #XXX this is the place to display a warning
        return self.box(real)

    @specialize.argtype(1)
    def unbox(self, box):
        assert isinstance(box, self.BoxType)
        return box.value

    def coerce(self, space, dtype, w_item):
        if isinstance(w_item, self.BoxType):
            return w_item
        return self.coerce_subtype(space, space.gettypefor(self.BoxType), w_item)

    def coerce_subtype(self, space, w_subtype, w_item):
        # XXX: ugly
        w_obj = space.allocate_instance(self.BoxType, w_subtype)
        assert isinstance(w_obj, self.BoxType)
        w_obj.__init__(self._coerce(space, w_item).value)
        return w_obj

    def to_builtin_type(self, space, box):
        return space.wrap(self.for_computation(self.unbox(box)))

    def _coerce(self, space, w_item):
        raise NotImplementedError

    def default_fromstring(self, space):
        raise NotImplementedError

    def _read(self, storage, i, offset):
        return raw_storage_getitem(self.T, storage, i + offset)

    def read(self, arr, i, offset, dtype=None):
        return self.box(self._read(arr.storage, i, offset))

    def read_bool(self, arr, i, offset):
        return bool(self.for_computation(self._read(arr.storage, i, offset)))

    def _write(self, storage, i, offset, value):
        raw_storage_setitem(storage, i + offset, value)

    def store(self, arr, i, offset, box):
        self._write(arr.storage, i, offset, self.unbox(box))

    def fill(self, storage, width, box, start, stop, offset):
        value = self.unbox(box)
        for i in xrange(start, stop, width):
            self._write(storage, i, offset, value)

    def runpack_str(self, s):
        v = runpack(self.format_code, s)
        return self.box(v)

    @simple_binary_op
    def add(self, v1, v2):
        return v1 + v2

    @simple_binary_op
    def sub(self, v1, v2):
        return v1 - v2

    @simple_binary_op
    def mul(self, v1, v2):
        return v1 * v2

    @simple_unary_op
    def pos(self, v):
        return +v

    @simple_unary_op
    def neg(self, v):
        return -v

    def byteswap(self, w_v):
        # no for_computation here
        return self.box(byteswap(self.unbox(w_v)))

    @simple_unary_op
    def conj(self, v):
        return v

    @simple_unary_op
    def real(self, v):
        return v

    @simple_unary_op
    def imag(self, v):
        return 0

    @simple_unary_op
    def abs(self, v):
        return abs(v)

    @raw_unary_op
    def isnan(self, v):
        return False

    @raw_unary_op
    def isinf(self, v):
        return False

    @raw_unary_op
    def isneginf(self, v):
        return False

    @raw_unary_op
    def isposinf(self, v):
        return False

    @raw_binary_op
    def eq(self, v1, v2):
        return v1 == v2

    @raw_binary_op
    def ne(self, v1, v2):
        return v1 != v2

    @raw_binary_op
    def lt(self, v1, v2):
        return v1 < v2

    @raw_binary_op
    def le(self, v1, v2):
        return v1 <= v2

    @raw_binary_op
    def gt(self, v1, v2):
        return v1 > v2

    @raw_binary_op
    def ge(self, v1, v2):
        return v1 >= v2

    @raw_binary_op
    def logical_and(self, v1, v2):
        return bool(v1) and bool(v2)

    @raw_binary_op
    def logical_or(self, v1, v2):
        return bool(v1) or bool(v2)

    @raw_unary_op
    def logical_not(self, v):
        return not bool(v)

    @raw_binary_op
    def logical_xor(self, v1, v2):
        return bool(v1) ^ bool(v2)

    def bool(self, v):
        return bool(self.for_computation(self.unbox(v)))

    @simple_binary_op
    def max(self, v1, v2):
        return max(v1, v2)

    @simple_binary_op
    def min(self, v1, v2):
        return min(v1, v2)

class NonNativePrimitive(Primitive):
    _mixin_ = True

    def _read(self, storage, i, offset):
        res = raw_storage_getitem(self.T, storage, i + offset)
        return byteswap(res)

    def _write(self, storage, i, offset, value):
        value = byteswap(value)
        raw_storage_setitem(storage, i + offset, value)

class Bool(BaseType, Primitive):
    _attrs_ = ()

    T = lltype.Bool
    BoxType = interp_boxes.W_BoolBox
    format_code = "?"

    True = BoxType(True)
    False = BoxType(False)

    @specialize.argtype(1)
    def box(self, value):
        box = Primitive.box(self, value)
        if box.value:
            return self.True
        else:
            return self.False

    @specialize.argtype(1, 2)
    def box_complex(self, real, imag):
        box = Primitive.box(self, real)
        if box.value:
            return self.True
        box = Primitive.box(self, imag)
        if box.value:
            return self.True
        return self.False

    def coerce_subtype(self, space, w_subtype, w_item):
        # Doesn't return subclasses so it can return the constants.
        return self._coerce(space, w_item)

    def _coerce(self, space, w_item):
        return self.box(space.is_true(w_item))

    def to_builtin_type(self, space, w_item):
        return space.wrap(self.unbox(w_item))

    def str_format(self, box):
        return "True" if self.unbox(box) else "False"

    @staticmethod
    def for_computation(v):
        return int(v)

    def default_fromstring(self, space):
        return self.box(True)

    @simple_binary_op
    def bitwise_and(self, v1, v2):
        return v1 & v2

    @simple_binary_op
    def bitwise_or(self, v1, v2):
        return v1 | v2

    @simple_binary_op
    def bitwise_xor(self, v1, v2):
        return v1 ^ v2

    @simple_unary_op
    def invert(self, v):
        return ~v

NonNativeBool = Bool

class Integer(Primitive):
    _mixin_ = True

    def _base_coerce(self, space, w_item):
        return self.box(space.int_w(space.call_function(space.w_int, w_item)))
    def _coerce(self, space, w_item):
        return self._base_coerce(space, w_item)

    def str_format(self, box):
        return str(self.for_computation(self.unbox(box)))

    @staticmethod
    def for_computation(v):
        return widen(v)

    def default_fromstring(self, space):
        return self.box(0)

    @simple_binary_op
    def div(self, v1, v2):
        if v2 == 0:
            return 0
        return v1 / v2

    @simple_binary_op
    def floordiv(self, v1, v2):
        if v2 == 0:
            return 0
        return v1 // v2

    @simple_binary_op
    def mod(self, v1, v2):
        return v1 % v2

    @simple_binary_op
    def pow(self, v1, v2):
        if v2 < 0:
            return 0
        res = 1
        while v2 > 0:
            if v2 & 1:
                res *= v1
            v2 >>= 1
            if v2 == 0:
                break
            v1 *= v1
        return res

    @simple_binary_op
    def lshift(self, v1, v2):
        return v1 << v2

    @simple_binary_op
    def rshift(self, v1, v2):
        return v1 >> v2

    @simple_unary_op
    def sign(self, v):
        if v > 0:
            return 1
        elif v < 0:
            return -1
        else:
            assert v == 0
            return 0

    @raw_unary_op
    def isfinite(self, v):
        return True

    @raw_unary_op
    def isnan(self, v):
        return False

    @raw_unary_op
    def isinf(self, v):
        return False

    @raw_unary_op
    def isposinf(self, v):
        return False

    @raw_unary_op
    def isneginf(self, v):
        return False

    @simple_binary_op
    def bitwise_and(self, v1, v2):
        return v1 & v2

    @simple_binary_op
    def bitwise_or(self, v1, v2):
        return v1 | v2

    @simple_binary_op
    def bitwise_xor(self, v1, v2):
        return v1 ^ v2

    @simple_unary_op
    def invert(self, v):
        return ~v

class NonNativeInteger(NonNativePrimitive, Integer):
    _mixin_ = True

class Int8(BaseType, Integer):
    _attrs_ = ()

    T = rffi.SIGNEDCHAR
    BoxType = interp_boxes.W_Int8Box
    format_code = "b"
NonNativeInt8 = Int8

class UInt8(BaseType, Integer):
    _attrs_ = ()

    T = rffi.UCHAR
    BoxType = interp_boxes.W_UInt8Box
    format_code = "B"
NonNativeUInt8 = UInt8

class Int16(BaseType, Integer):
    _attrs_ = ()

    T = rffi.SHORT
    BoxType = interp_boxes.W_Int16Box
    format_code = "h"

class NonNativeInt16(BaseType, NonNativeInteger):
    _attrs_ = ()

    T = rffi.SHORT
    BoxType = interp_boxes.W_Int16Box
    format_code = "h"

class UInt16(BaseType, Integer):
    _attrs_ = ()

    T = rffi.USHORT
    BoxType = interp_boxes.W_UInt16Box
    format_code = "H"

class NonNativeUInt16(BaseType, NonNativeInteger):
    _attrs_ = ()

    T = rffi.USHORT
    BoxType = interp_boxes.W_UInt16Box
    format_code = "H"

class Int32(BaseType, Integer):
    _attrs_ = ()

    T = rffi.INT
    BoxType = interp_boxes.W_Int32Box
    format_code = "i"

class NonNativeInt32(BaseType, NonNativeInteger):
    _attrs_ = ()

    T = rffi.INT
    BoxType = interp_boxes.W_Int32Box
    format_code = "i"

class UInt32(BaseType, Integer):
    _attrs_ = ()

    T = rffi.UINT
    BoxType = interp_boxes.W_UInt32Box
    format_code = "I"

class NonNativeUInt32(BaseType, NonNativeInteger):
    _attrs_ = ()

    T = rffi.UINT
    BoxType = interp_boxes.W_UInt32Box
    format_code = "I"

class Long(BaseType, Integer):
    _attrs_ = ()

    T = rffi.LONG
    BoxType = interp_boxes.W_LongBox
    format_code = "l"

class NonNativeLong(BaseType, NonNativeInteger):
    _attrs_ = ()

    T = rffi.LONG
    BoxType = interp_boxes.W_LongBox
    format_code = "l"

class ULong(BaseType, Integer):
    _attrs_ = ()

    T = rffi.ULONG
    BoxType = interp_boxes.W_ULongBox
    format_code = "L"

class NonNativeULong(BaseType, NonNativeInteger):
    _attrs_ = ()

    T = rffi.ULONG
    BoxType = interp_boxes.W_ULongBox
    format_code = "L"

def _int64_coerce(self, space, w_item):
    try:
        return self._base_coerce(space, w_item)
    except OperationError, e:
        if not e.match(space, space.w_OverflowError):
            raise
    bigint = space.bigint_w(w_item)
    try:
        value = bigint.tolonglong()
    except OverflowError:
        raise OperationError(space.w_OverflowError, space.w_None)
    return self.box(value)

class Int64(BaseType, Integer):
    _attrs_ = ()

    T = rffi.LONGLONG
    BoxType = interp_boxes.W_Int64Box
    format_code = "q"

    _coerce = func_with_new_name(_int64_coerce, '_coerce')

class NonNativeInt64(BaseType, NonNativeInteger):
    _attrs_ = ()

    T = rffi.LONGLONG
    BoxType = interp_boxes.W_Int64Box
    format_code = "q"

    _coerce = func_with_new_name(_int64_coerce, '_coerce')

def _uint64_coerce(self, space, w_item):
    try:
        return self._base_coerce(space, w_item)
    except OperationError, e:
        if not e.match(space, space.w_OverflowError):
            raise
    bigint = space.bigint_w(w_item)
    try:
        value = bigint.toulonglong()
    except OverflowError:
        raise OperationError(space.w_OverflowError, space.w_None)
    return self.box(value)

class UInt64(BaseType, Integer):
    _attrs_ = ()

    T = rffi.ULONGLONG
    BoxType = interp_boxes.W_UInt64Box
    format_code = "Q"

    _coerce = func_with_new_name(_uint64_coerce, '_coerce')

class NonNativeUInt64(BaseType, NonNativeInteger):
    _attrs_ = ()

    T = rffi.ULONGLONG
    BoxType = interp_boxes.W_UInt64Box
    format_code = "Q"

    _coerce = func_with_new_name(_uint64_coerce, '_coerce')

class Float(Primitive):
    _mixin_ = True

    def _coerce(self, space, w_item):
        if space.is_none(w_item):
            return self.box(rfloat.NAN)
        return self.box(space.float_w(space.call_function(space.w_float, w_item)))

    def str_format(self, box):
        return float2string(self.for_computation(self.unbox(box)), "g",
                            rfloat.DTSF_STR_PRECISION)

    @staticmethod
    def for_computation(v):
        return float(v)

    def default_fromstring(self, space):
        return self.box(-1.0)

    @simple_binary_op
    def div(self, v1, v2):
        try:
            return v1 / v2
        except ZeroDivisionError:
            if v1 == v2 == 0.0:
                return rfloat.NAN
            return rfloat.copysign(rfloat.INFINITY, v1 * v2)

    @simple_binary_op
    def floordiv(self, v1, v2):
        try:
            return math.floor(v1 / v2)
        except ZeroDivisionError:
            if v1 == v2 == 0.0:
                return rfloat.NAN
            return rfloat.copysign(rfloat.INFINITY, v1 * v2)

    @simple_binary_op
    def mod(self, v1, v2):
        return math.fmod(v1, v2)

    @simple_binary_op
    def pow(self, v1, v2):
        try:
            return math.pow(v1, v2)
        except ValueError:
            return rfloat.NAN
        except OverflowError:
            if math.modf(v2)[0] == 0 and math.modf(v2 / 2)[0] != 0:
                # Odd integer powers result in the same sign as the base
                return rfloat.copysign(rfloat.INFINITY, v1)
            return rfloat.INFINITY

    @simple_binary_op
    def copysign(self, v1, v2):
        return math.copysign(v1, v2)

    @simple_unary_op
    def sign(self, v):
        if v == 0.0:
            return 0.0
        return rfloat.copysign(1.0, v)

    @raw_unary_op
    def signbit(self, v):
        return rfloat.copysign(1.0, v) < 0.0

    @simple_unary_op
    def fabs(self, v):
        return math.fabs(v)

    @simple_binary_op
    def fmax(self, v1, v2):
        if rfloat.isnan(v2):
            return v1
        elif rfloat.isnan(v1):
            return v2
        return max(v1, v2)

    @simple_binary_op
    def fmin(self, v1, v2):
        if rfloat.isnan(v2):
            return v1
        elif rfloat.isnan(v1):
            return v2
        return min(v1, v2)

    @simple_binary_op
    def fmod(self, v1, v2):
        try:
            return math.fmod(v1, v2)
        except ValueError:
            return rfloat.NAN

    @simple_unary_op
    def reciprocal(self, v):
        if v == 0.0:
            return rfloat.copysign(rfloat.INFINITY, v)
        return 1.0 / v

    @simple_unary_op
    def floor(self, v):
        return math.floor(v)

    @simple_unary_op
    def ceil(self, v):
        return math.ceil(v)

    @simple_unary_op
    def trunc(self, v):
        if v < 0:
            return math.ceil(v)
        else:
            return math.floor(v)

    @simple_unary_op
    def exp(self, v):
        try:
            return math.exp(v)
        except OverflowError:
            return rfloat.INFINITY

    @simple_unary_op
    def exp2(self, v):
        try:
            return math.pow(2, v)
        except OverflowError:
            return rfloat.INFINITY

    @simple_unary_op
    def expm1(self, v):
        try:
            return rfloat.expm1(v)
        except OverflowError:
            return rfloat.INFINITY

    @simple_unary_op
    def sin(self, v):
        return math.sin(v)

    @simple_unary_op
    def cos(self, v):
        return math.cos(v)

    @simple_unary_op
    def tan(self, v):
        return math.tan(v)

    @simple_unary_op
    def arcsin(self, v):
        if not -1.0 <= v <= 1.0:
            return rfloat.NAN
        return math.asin(v)

    @simple_unary_op
    def arccos(self, v):
        if not -1.0 <= v <= 1.0:
            return rfloat.NAN
        return math.acos(v)

    @simple_unary_op
    def arctan(self, v):
        return math.atan(v)

    @simple_binary_op
    def arctan2(self, v1, v2):
        return math.atan2(v1, v2)

    @simple_unary_op
    def sinh(self, v):
        return math.sinh(v)

    @simple_unary_op
    def cosh(self, v):
        return math.cosh(v)

    @simple_unary_op
    def tanh(self, v):
        return math.tanh(v)

    @simple_unary_op
    def arcsinh(self, v):
        return math.asinh(v)

    @simple_unary_op
    def arccosh(self, v):
        if v < 1.0:
            return rfloat.NAN
        return math.acosh(v)

    @simple_unary_op
    def arctanh(self, v):
        if v == 1.0 or v == -1.0:
            return math.copysign(rfloat.INFINITY, v)
        if not -1.0 < v < 1.0:
            return rfloat.NAN
        return math.atanh(v)

    @simple_unary_op
    def sqrt(self, v):
        try:
            return math.sqrt(v)
        except ValueError:
            return rfloat.NAN

    @simple_unary_op
    def square(self, v):
        return v*v

    @raw_unary_op
    def isnan(self, v):
        return rfloat.isnan(v)

    @raw_unary_op
    def isinf(self, v):
        return rfloat.isinf(v)

    @raw_unary_op
    def isneginf(self, v):
        return rfloat.isinf(v) and v < 0

    @raw_unary_op
    def isposinf(self, v):
        return rfloat.isinf(v) and v > 0

    @raw_unary_op
    def isfinite(self, v):
        return not (rfloat.isinf(v) or rfloat.isnan(v))

    @simple_unary_op
    def radians(self, v):
        return v * degToRad
    deg2rad = radians

    @simple_unary_op
    def degrees(self, v):
        return v / degToRad

    @simple_unary_op
    def log(self, v):
        try:
            return math.log(v)
        except ValueError:
            if v == 0.0:
                # CPython raises ValueError here, so we have to check
                # the value to find the correct numpy return value
                return -rfloat.INFINITY
            return rfloat.NAN

    @simple_unary_op
    def log2(self, v):
        try:
            return math.log(v) / log2
        except ValueError:
            if v == 0.0:
                # CPython raises ValueError here, so we have to check
                # the value to find the correct numpy return value
                return -rfloat.INFINITY
            return rfloat.NAN

    @simple_unary_op
    def log10(self, v):
        try:
            return math.log10(v)
        except ValueError:
            if v == 0.0:
                # CPython raises ValueError here, so we have to check
                # the value to find the correct numpy return value
                return -rfloat.INFINITY
            return rfloat.NAN

    @simple_unary_op
    def log1p(self, v):
        try:
            return rfloat.log1p(v)
        except OverflowError:
            return -rfloat.INFINITY
        except ValueError:
            return rfloat.NAN

    @simple_binary_op
    def logaddexp(self, v1, v2):
        tmp = v1 - v2
        if tmp > 0:
            return v1 + rfloat.log1p(math.exp(-tmp))
        elif tmp <= 0:
            return v2 + rfloat.log1p(math.exp(tmp))
        else:
            return v1 + v2

    def npy_log2_1p(self, v):
        return log2e * rfloat.log1p(v)

    @simple_binary_op
    def logaddexp2(self, v1, v2):
        tmp = v1 - v2
        if tmp > 0:
            return v1 + self.npy_log2_1p(math.pow(2, -tmp))
        if tmp <= 0:
            return v2 + self.npy_log2_1p(math.pow(2, tmp))
        else:
            return v1 + v2

class NonNativeFloat(NonNativePrimitive, Float):
    _mixin_ = True

    def _read(self, storage, i, offset):
        res = raw_storage_getitem(self.T, storage, i + offset)
        return rffi.cast(lltype.Float, byteswap(res))

    def _write(self, storage, i, offset, value):
        swapped_value = byteswap(rffi.cast(self.T, value))
        raw_storage_setitem(storage, i + offset, swapped_value)

class Float32(BaseType, Float):
    _attrs_ = ()

    T = rffi.FLOAT
    BoxType = interp_boxes.W_Float32Box
    format_code = "f"

class NonNativeFloat32(BaseType, NonNativeFloat):
    _attrs_ = ()

    T = rffi.FLOAT
    BoxType = interp_boxes.W_Float32Box
    format_code = "f"

    def read_bool(self, arr, i, offset):
        # it's not clear to me why this is needed
        # but a hint might be that calling for_computation(v)
        # causes translation to fail, and the assert is necessary
        v = self._read(arr.storage, i, offset)
        assert isinstance(v, float)
        return bool(v)

class Float64(BaseType, Float):
    _attrs_ = ()

    T = rffi.DOUBLE
    BoxType = interp_boxes.W_Float64Box
    format_code = "d"

class NonNativeFloat64(BaseType, NonNativeFloat):
    _attrs_ = ()

    T = rffi.DOUBLE
    BoxType = interp_boxes.W_Float64Box
    format_code = "d"

class ComplexFloating(object):
    _mixin_ = True
    _attrs_ = ()

    def _coerce(self, space, w_item):
        w_item = space.call_function(space.w_complex, w_item)
        real, imag = space.unpackcomplex(w_item)
        return self.box_complex(real, imag)

    def coerce(self, space, dtype, w_item):
        if isinstance(w_item, self.BoxType):
            return w_item
        return self.coerce_subtype(space, space.gettypefor(self.BoxType), w_item)

    def coerce_subtype(self, space, w_subtype, w_item):
        w_tmpobj = self._coerce(space, w_item)
        w_obj = space.allocate_instance(self.BoxType, w_subtype)
        assert isinstance(w_obj, self.BoxType)
        w_obj.__init__(w_tmpobj.real, w_tmpobj.imag)
        return w_obj

    def str_format(self, box):
        real, imag = self.for_computation(self.unbox(box))
        imag_str = str_format(imag) + 'j'

        # (0+2j) => 2j
        if real == 0:
            return imag_str

        real_str = str_format(real)
        op = '+' if imag >= 0 else ''
        return ''.join(['(', real_str, op, imag_str, ')'])

    @staticmethod
    def for_computation(v):
        return float(v[0]), float(v[1])

    @raw_unary_op
    def _to_builtin_type(self, v):
        return v

    def to_builtin_type(self, space, box):
        real,imag = self.for_computation(self.unbox(box))
        return space.newcomplex(real, imag) 

    def read_bool(self, arr, i, offset):
        v = self.for_computation(self._read(arr.storage, i, offset))
        return bool(v[0]) or bool(v[1])

    def get_element_size(self):
        return 2 * rffi.sizeof(self.T)

    def byteswap(self, w_v):
        real, imag = self.unbox(w_v)
        return self.box_complex(byteswap(real), byteswap(imag))

    @specialize.argtype(1)
    def box(self, value):
        return self.BoxType(
            rffi.cast(self.T, value),
            rffi.cast(self.T, 0.0))

    @specialize.argtype(1)
    def box_component(self, value):
        return self.ComponentBoxType(
            rffi.cast(self.T, value))

    @specialize.argtype(1, 2)
    def box_complex(self, real, imag):
        return self.BoxType(
            rffi.cast(self.T, real),
            rffi.cast(self.T, imag))

    def unbox(self, box):
        assert isinstance(box, self.BoxType)
        # do this in two stages since real, imag are read only
        real, imag = box.real, box.imag
        return real, imag

    def store(self, arr, i, offset, box):
        real, imag = self.unbox(box)
        raw_storage_setitem(arr.storage, i+offset, real)
        raw_storage_setitem(arr.storage,
                i+offset+rffi.sizeof(self.T), imag)

    def _read(self, storage, i, offset):
        real = raw_storage_getitem(self.T, storage, i + offset)
        imag = raw_storage_getitem(self.T, storage,
                              i + offset + rffi.sizeof(self.T))
        return real, imag

    def read(self, arr, i, offset, dtype=None):
        real, imag = self._read(arr.storage, i, offset)
        return self.box_complex(real, imag)

    @complex_binary_op
    def add(self, v1, v2):
        return rcomplex.c_add(v1, v2)

    @complex_binary_op
    def sub(self, v1, v2):
        return rcomplex.c_sub(v1, v2)

    @complex_binary_op
    def mul(self, v1, v2):
        return rcomplex.c_mul(v1, v2)

    @complex_binary_op
    def div(self, v1, v2):
        try:
            return rcomplex.c_div(v1, v2)
        except ZeroDivisionError:
            if rcomplex.c_abs(*v1) == 0:
                return rfloat.NAN, rfloat.NAN
            return rfloat.INFINITY, rfloat.INFINITY

    @complex_unary_op
    def pos(self, v):
        return v

    @complex_unary_op
    def neg(self, v):
        return -v[0], -v[1]

    @complex_unary_op
    def conj(self, v):
        return v[0], -v[1]

    @complex_to_real_unary_op
    def real(self, v):
        return v[0]

    @complex_to_real_unary_op
    def imag(self, v):
        return v[1]

    @complex_to_real_unary_op
    def abs(self, v):
        return rcomplex.c_abs(v[0], v[1])

    @raw_unary_op
    def isnan(self, v):
        '''a complex number is nan if one of the parts is nan'''
        return rfloat.isnan(v[0]) or rfloat.isnan(v[1])

    @raw_unary_op
    def isinf(self, v):
        '''a complex number is inf if one of the parts is inf'''
        return rfloat.isinf(v[0]) or rfloat.isinf(v[1])

    def _eq(self, v1, v2):
        return v1[0] == v2[0] and v1[1] == v2[1]

    @raw_binary_op
    def eq(self, v1, v2):
        #compare the parts, so nan == nan is False
        return self._eq(v1, v2)

    @raw_binary_op
    def ne(self, v1, v2):
        return not self._eq(v1, v2)

    def _lt(self, v1, v2):
        (r1, i1), (r2, i2) = v1, v2
        if r1 < r2:
            return True
        elif not r1 <= r2:
            return False
        return i1 < i2

    @raw_binary_op
    def lt(self, v1, v2):
        return self._lt(v1, v2)

    @raw_binary_op
    def le(self, v1, v2):
        return self._lt(v1, v2) or self._eq(v1, v2) 

    @raw_binary_op
    def gt(self, v1, v2):
        return self._lt(v2, v1)

    @raw_binary_op
    def ge(self, v1, v2):
        return self._lt(v2, v1) or self._eq(v2, v1) 

    def _bool(self, v):
        return bool(v[0]) or bool(v[1])

    @raw_binary_op
    def logical_and(self, v1, v2):
        return self._bool(v1) and self._bool(v2)

    @raw_binary_op
    def logical_or(self, v1, v2):
        return self._bool(v1) or self._bool(v2)

    @raw_unary_op
    def logical_not(self, v):
        return not self._bool(v)

    @raw_binary_op
    def logical_xor(self, v1, v2):
        return self._bool(v1) ^ self._bool(v2)

    def min(self, v1, v2):
        return self.fmin(v1, v2)

    def max(self, v1, v2):
        return self.fmax(v1, v2)

    @complex_binary_op
    def floordiv(self, v1, v2):
        try:
            ab = v1[0]*v2[0] + v1[1]*v2[1]
            bb = v2[0]*v2[0] + v2[1]*v2[1]
            return math.floor(ab/bb), 0.
        except ZeroDivisionError:
            return rfloat.NAN, 0.

    #complex mod does not exist in numpy
    #@simple_binary_op
    #def mod(self, v1, v2):
    #    return math.fmod(v1, v2)

    @complex_binary_op
    def pow(self, v1, v2):
        if v1[1] == 0 and v2[1] == 0 and v1[0] > 0:
            return math.pow(v1[0], v2[0]), 0
        #if not isfinite(v1[0]) or not isfinite(v1[1]):
        #    return rfloat.NAN, rfloat.NAN
        try:
            return rcomplex.c_pow(v1, v2)
        except ZeroDivisionError:
            return rfloat.NAN, rfloat.NAN
        except OverflowError:
            return rfloat.INFINITY, -math.copysign(rfloat.INFINITY, v1[1])
        except ValueError:
            return rfloat.NAN, rfloat.NAN


    #complex copysign does not exist in numpy
    #@complex_binary_op
    #def copysign(self, v1, v2):
    #    return (rfloat.copysign(v1[0], v2[0]),
    #           rfloat.copysign(v1[1], v2[1]))

    @complex_unary_op
    def sign(self, v):
        '''
        sign of complex number could be either the point closest to the unit circle
        or {-1,0,1}, for compatability with numpy we choose the latter
        '''
        if v[0] == 0.0:
            if v[1] == 0:
                return 0,0
            if v[1] > 0:
                return 1,0
            return -1,0
        if v[0] > 0:
            return 1,0
        return -1,0

    def fmax(self, v1, v2):
        if self.isnan(v2):
            return v1
        elif self.isnan(v1):
            return v2
        if self.ge(v1, v2):
            return v1
        return v2

    def fmin(self, v1, v2):
        if self.isnan(v2):
            return v1
        elif self.isnan(v1):
            return v2
        if self.le(v1, v2):
            return v1
        return v2

    #@simple_binary_op
    #def fmod(self, v1, v2):
    #    try:
    #        return math.fmod(v1, v2)
    #    except ValueError:
    #        return rfloat.NAN

    @complex_unary_op
    def reciprocal(self, v):
        if rfloat.isinf(v[1]) and rfloat.isinf(v[0]):
            return rfloat.NAN, rfloat.NAN
        if rfloat.isinf(v[0]):
            return (rfloat.copysign(0., v[0]),
                    rfloat.copysign(0., -v[1]))
        a2 = v[0]*v[0] + v[1]*v[1]
        try:
            return rcomplex.c_div((v[0], -v[1]), (a2, 0.))
        except ZeroDivisionError:
            return rfloat.NAN, rfloat.NAN
 
    # No floor, ceil, trunc in numpy for complex
    #@simple_unary_op
    #def floor(self, v):
    #    return math.floor(v)

    #@simple_unary_op
    #def ceil(self, v):
    #    return math.ceil(v)

    #@simple_unary_op
    #def trunc(self, v):
    #    if v < 0:
    #        return math.ceil(v)
    #    else:
    #        return math.floor(v)

    @complex_unary_op
    def exp(self, v):
        if rfloat.isinf(v[1]):
            if rfloat.isinf(v[0]):
                if v[0] < 0:
                    return 0., 0.
                return rfloat.INFINITY, rfloat.NAN
            elif (isfinite(v[0]) or \
                                 (rfloat.isinf(v[0]) and v[0] > 0)):
                return rfloat.NAN, rfloat.NAN
        try:
            return rcomplex.c_exp(*v)
        except OverflowError:
            if v[1] == 0:
                return rfloat.INFINITY, 0.0
            return rfloat.INFINITY, rfloat.NAN

    @complex_unary_op
    def exp2(self, v):
        try:
            return rcomplex.c_pow((2,0), v)
        except OverflowError:
            return rfloat.INFINITY, rfloat.NAN
        except ValueError:
            return rfloat.NAN, rfloat.NAN

    @complex_unary_op
    def expm1(self, v):
        # duplicate exp() so in the future it will be easier
        # to implement seterr
        if rfloat.isinf(v[1]):
            if rfloat.isinf(v[0]):
                if v[0] < 0:
                    return -1., 0.
                return rfloat.NAN, rfloat.NAN
            elif (isfinite(v[0]) or \
                                 (rfloat.isinf(v[0]) and v[0] > 0)):
                return rfloat.NAN, rfloat.NAN
        try:
            res = rcomplex.c_exp(*v)
            res = (res[0]-1, res[1])
            return res
        except OverflowError:
            if v[1] == 0:
                return rfloat.INFINITY, 0.0
            return rfloat.INFINITY, rfloat.NAN

    @complex_unary_op
    def sin(self, v):
        if rfloat.isinf(v[0]):
            if v[1] == 0.:
                return rfloat.NAN, 0.
            if isfinite(v[1]):
                return rfloat.NAN, rfloat.NAN
            elif not rfloat.isnan(v[1]):
                return rfloat.NAN, rfloat.INFINITY
        return rcomplex.c_sin(*v)

    @complex_unary_op
    def cos(self, v):
        if rfloat.isinf(v[0]):
            if v[1] == 0.:
                return rfloat.NAN, 0.0
            if isfinite(v[1]):
                return rfloat.NAN, rfloat.NAN
            elif not rfloat.isnan(v[1]):
                return rfloat.INFINITY, rfloat.NAN
        return rcomplex.c_cos(*v)

    @complex_unary_op
    def tan(self, v):
        if rfloat.isinf(v[0]) and isfinite(v[1]):
            return rfloat.NAN, rfloat.NAN
        return rcomplex.c_tan(*v)

    @complex_unary_op
    def arcsin(self, v):
        return rcomplex.c_asin(*v)

    @complex_unary_op
    def arccos(self, v):
        return rcomplex.c_acos(*v)

    @complex_unary_op
    def arctan(self, v):
        if v[0] == 0 and (v[1] == 1 or v[1] == -1):
            #This is the place to print a "runtime warning"
            return rfloat.NAN, math.copysign(rfloat.INFINITY, v[1])
        return rcomplex.c_atan(*v)

    #@complex_binary_op
    #def arctan2(self, v1, v2):
    #    return rcomplex.c_atan2(v1, v2)

    @complex_unary_op
    def sinh(self, v):
        if rfloat.isinf(v[1]):
            if isfinite(v[0]):
                if v[0] == 0.0:
                    return 0.0, rfloat.NAN
                return rfloat.NAN, rfloat.NAN
            elif not rfloat.isnan(v[0]):
                return rfloat.INFINITY, rfloat.NAN
        return rcomplex.c_sinh(*v)

    @complex_unary_op
    def cosh(self, v):
        if rfloat.isinf(v[1]):
            if isfinite(v[0]):
                if v[0] == 0.0:
                    return rfloat.NAN, 0.0
                return rfloat.NAN, rfloat.NAN
            elif not rfloat.isnan(v[0]):
                return rfloat.INFINITY, rfloat.NAN
        return rcomplex.c_cosh(*v)

    @complex_unary_op
    def tanh(self, v):
        if rfloat.isinf(v[1]) and isfinite(v[0]):
            return rfloat.NAN, rfloat.NAN
        return rcomplex.c_tanh(*v)

    @complex_unary_op
    def arcsinh(self, v):
        return rcomplex.c_asinh(*v)

    @complex_unary_op
    def arccosh(self, v):
        return rcomplex.c_acosh(*v)

    @complex_unary_op
    def arctanh(self, v):
        if v[1] == 0 and (v[0] == 1.0 or v[0] == -1.0):
            return (math.copysign(rfloat.INFINITY, v[0]),
                   math.copysign(0., v[1]))
        return rcomplex.c_atanh(*v)

    @complex_unary_op
    def sqrt(self, v):
        return rcomplex.c_sqrt(*v)

    @complex_unary_op
    def square(self, v):
        return rcomplex.c_mul(v,v)

    @raw_unary_op
    def isfinite(self, v):
        return isfinite(v[0]) and isfinite(v[1])

    #@simple_unary_op
    #def radians(self, v):
    #    return v * degToRad
    #deg2rad = radians

    #@simple_unary_op
    #def degrees(self, v):
    #    return v / degToRad

    @complex_unary_op
    def log(self, v):
        if v[0] == 0 and v[1] == 0:
            return -rfloat.INFINITY, 0
        return rcomplex.c_log(*v)

    @complex_unary_op
    def log2(self, v):
        if v[0] == 0 and v[1] == 0:
            return -rfloat.INFINITY, 0
        r = rcomplex.c_log(*v)
        return r[0] / log2, r[1] / log2

    @complex_unary_op
    def log10(self, v):
        if v[0] == 0 and v[1] == 0:
            return -rfloat.INFINITY, 0
        return rcomplex.c_log10(*v)

    @complex_unary_op
    def log1p(self, v):
        try:
            return rcomplex.c_log(v[0] + 1, v[1])
        except OverflowError:
            return -rfloat.INFINITY, 0
        except ValueError:
            return rfloat.NAN, rfloat.NAN

class Complex64(ComplexFloating, BaseType):
    _attrs_ = ()

    T = rffi.FLOAT
    BoxType = interp_boxes.W_Complex64Box
    ComponentBoxType = interp_boxes.W_Float32Box

NonNativeComplex64 = Complex64

class Complex128(ComplexFloating, BaseType):
    _attrs_ = ()

    T = rffi.DOUBLE
    BoxType = interp_boxes.W_Complex128Box
    ComponentBoxType = interp_boxes.W_Float64Box

NonNativeComplex128 = Complex128

if interp_boxes.long_double_size == 12:
    class Float96(BaseType, Float):
        _attrs_ = ()

        T = rffi.LONGDOUBLE
        BoxType = interp_boxes.W_Float96Box
        format_code = "q"

        def runpack_str(self, s):
            assert len(s) == 12
            fval = unpack_float80(s, native_is_bigendian)
            return self.box(fval)

        def byteswap(self, w_v):
            value = self.unbox(w_v)
            result = StringBuilder(10)
            pack_float80(result, value, 10, not native_is_bigendian)
            return self.box(unpack_float80(result.build(), native_is_bigendian))

    NonNativeFloat96 = Float96

    class Complex192(ComplexFloating, BaseType):
        _attrs_ = ()

        T = rffi.LONGDOUBLE
        BoxType = interp_boxes.W_Complex192Box
        ComponentBoxType = interp_boxes.W_Float96Box

    NonNativeComplex192 = Complex192

elif interp_boxes.long_double_size == 16:
    class Float128(BaseType, Float):
        _attrs_ = ()

        T = rffi.LONGDOUBLE
        BoxType = interp_boxes.W_Float128Box
        format_code = "q"

        def runpack_str(self, s):
            assert len(s) == 16
            fval = unpack_float80(s, native_is_bigendian)
            return self.box(fval)

        def byteswap(self, w_v):
            value = self.unbox(w_v)
            result = StringBuilder(10)
            pack_float80(result, value, 10, not native_is_bigendian)
            return self.box(unpack_float80(result.build(), native_is_bigendian))

    NonNativeFloat128 = Float128

    class Complex256(ComplexFloating, BaseType):
        _attrs_ = ()

        T = rffi.LONGDOUBLE
        BoxType = interp_boxes.W_Complex256Box
        ComponentBoxType = interp_boxes.W_Float128Box

    NonNativeComplex256 = Complex256

class BaseStringType(object):
    _mixin_ = True

    def __init__(self, size=0):
        self.size = size

    def get_element_size(self):
        return self.size * rffi.sizeof(self.T)

    def get_size(self):
        return self.size

class StringType(BaseType, BaseStringType):
    T = lltype.Char

    @jit.unroll_safe
    def coerce(self, space, dtype, w_item):
        from pypy.module.micronumpy.interp_dtype import new_string_dtype
        arg = space.str_w(space.str(w_item))
        arr = interp_boxes.VoidBoxStorage(len(arg), new_string_dtype(space, len(arg)))
        for i in range(len(arg)):
            arr.storage[i] = arg[i]
        return interp_boxes.W_StringBox(arr,  0, arr.dtype)

    @jit.unroll_safe
    def store(self, arr, i, offset, box):
        assert isinstance(box, interp_boxes.W_StringBox)
        for k in range(min(self.size, box.arr.size-offset)):
            arr.storage[k + i] = box.arr.storage[k + offset]

    def read(self, arr, i, offset, dtype=None):
        if dtype is None:
            dtype = arr.dtype
        return interp_boxes.W_StringBox(arr, i + offset, dtype)

    @jit.unroll_safe
    def to_str(self, item):
        builder = StringBuilder()
        assert isinstance(item, interp_boxes.W_StringBox)
        i = item.ofs
        end = i+self.size
        while i < end:
            assert isinstance(item.arr.storage[i], str)
            if item.arr.storage[i] == '\x00':
                break
            builder.append(item.arr.storage[i])
            i += 1
        return builder.build()

    def str_format(self, item):
        builder = StringBuilder()
        builder.append("'")
        builder.append(self.to_str(item))
        builder.append("'")
        return builder.build()

    # XXX move to base class when UnicodeType is supported
    def to_builtin_type(self, space, box):
        return space.wrap(self.to_str(box))

class VoidType(BaseType, BaseStringType):
    T = lltype.Char

NonNativeVoidType = VoidType
NonNativeStringType = StringType

class UnicodeType(BaseType, BaseStringType):
    T = lltype.UniChar

NonNativeUnicodeType = UnicodeType

class RecordType(BaseType):

    T = lltype.Char

    def __init__(self, offsets_and_fields, size):
        self.offsets_and_fields = offsets_and_fields
        self.size = size

    def get_element_size(self):
        return self.size

    def read(self, arr, i, offset, dtype=None):
        if dtype is None:
            dtype = arr.dtype
        return interp_boxes.W_VoidBox(arr, i + offset, dtype)

    @jit.unroll_safe
    def coerce(self, space, dtype, w_item):
        if isinstance(w_item, interp_boxes.W_VoidBox):
            return w_item
        # we treat every sequence as sequence, no special support
        # for arrays
        if not space.issequence_w(w_item):
            raise OperationError(space.w_TypeError, space.wrap(
                "expected sequence"))
        if len(self.offsets_and_fields) != space.int_w(space.len(w_item)):
            raise OperationError(space.w_ValueError, space.wrap(
                "wrong length"))
        items_w = space.fixedview(w_item)
        arr = VoidBoxStorage(self.size, dtype)
        for i in range(len(items_w)):
            subdtype = dtype.fields[dtype.fieldnames[i]][1]
            ofs, itemtype = self.offsets_and_fields[i]
            w_item = items_w[i]
            w_box = itemtype.coerce(space, subdtype, w_item)
            itemtype.store(arr, 0, ofs, w_box)
        return interp_boxes.W_VoidBox(arr, 0, dtype)

    @jit.unroll_safe
    def store(self, arr, i, ofs, box):
        assert isinstance(box, interp_boxes.W_VoidBox)
        for k in range(self.get_element_size()):
            arr.storage[k + i] = box.arr.storage[k + box.ofs]

    @jit.unroll_safe
    def str_format(self, box):
        assert isinstance(box, interp_boxes.W_VoidBox)
        pieces = ["("]
        first = True
        for ofs, tp in self.offsets_and_fields:
            if first:
                first = False
            else:
                pieces.append(", ")
            pieces.append(tp.str_format(tp.read(box.arr, box.ofs, ofs)))
        pieces.append(")")
        return "".join(pieces)

for tp in [Int32, Int64]:
    if tp.T == lltype.Signed:
        IntP = tp
        break
for tp in [UInt32, UInt64]:
    if tp.T == lltype.Unsigned:
        UIntP = tp
        break
del tp

all_float_types = []
all_int_types = []
all_complex_types = []

def for_int_computation(v):
    return widen(v)

def for_float_computation(v):
    return float(v)

def for_complex_computation(v):
    return float(v[0]), float(v[1])

def _setup():
    # compute alignment
    for tp in globals().values():
        if isinstance(tp, type) and hasattr(tp, 'T'):
            tp.alignment = clibffi.cast_type_to_ffitype(tp.T).c_alignment
            if issubclass(tp, Float):
                all_float_types.append((tp, 'float'))
            if issubclass(tp, Integer):
                all_int_types.append((tp, 'int'))
            if issubclass(tp, ComplexFloating):
                all_complex_types.append((tp, 'complex'))
_setup()
del _setup

class BaseFloat16(Float):
    _mixin_ = True

    _attrs_ = ()
    _STORAGE_T = rffi.USHORT
    T = rffi.SHORT

    BoxType = interp_boxes.W_Float16Box

    @specialize.argtype(1)
    def box(self, value):
        return self.BoxType(rffi.cast(rffi.DOUBLE, value))

    def runpack_str(self, s):
        assert len(s) == 2
        fval = unpack_float(s, native_is_bigendian)
        return self.box(fval)

    def default_fromstring(self, space):
        return self.box(-1.0)

    def byteswap(self, w_v):
        value = self.unbox(w_v)
        hbits = float_pack(value,2)
        swapped = byteswap(rffi.cast(self._STORAGE_T, hbits))
        return self.box(float_unpack(r_ulonglong(swapped), 2))

class Float16(BaseType, BaseFloat16):
    def _read(self, storage, i, offset):
        hbits = raw_storage_getitem(self._STORAGE_T, storage, i + offset)
        return float_unpack(r_ulonglong(hbits), 2)

    def _write(self, storage, i, offset, value):
        hbits = float_pack(value,2)
        raw_storage_setitem(storage, i + offset,
                rffi.cast(self._STORAGE_T, hbits))    

class NonNativeFloat16(BaseType, BaseFloat16):
    def _read(self, storage, i, offset):
        hbits = raw_storage_getitem(self._STORAGE_T, storage, i + offset)
        return float_unpack(r_ulonglong(byteswap(hbits)), 2)

    def _write(self, storage, i, offset, value):
        hbits = float_pack(value,2)
        raw_storage_setitem(storage, i + offset,
                byteswap(rffi.cast(self._STORAGE_T, hbits)))
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.