long.cpp 14.3 KB
Newer Older
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
// Copyright (c) 2014 Dropbox, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "runtime/long.h"

#include <cmath>
#include <gmp.h>
#include <sstream>

#include "codegen/compvars.h"
#include "core/common.h"
#include "core/options.h"
#include "core/stats.h"
#include "core/types.h"
#include "gc/collector.h"
#include "runtime/inline/boxing.h"
#include "runtime/objmodel.h"
#include "runtime/types.h"
#include "runtime/util.h"

namespace pyston {

BoxedClass* long_cls;

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
static int64_t asSignedLong(BoxedLong* self) {
    assert(self->cls == long_cls);
    if (!mpz_fits_slong_p(self->n))
        raiseExcHelper(OverflowError, "long int too large to convert to int");
    return mpz_get_si(self->n);
}

static uint64_t asUnsignedLong(BoxedLong* self) {
    assert(self->cls == long_cls);

    // if this is ever true, we should raise a Python error, but I don't think we should hit it?
    assert(mpz_cmp_si(self->n, 0) >= 0);

    if (!mpz_fits_ulong_p(self->n))
        raiseExcHelper(OverflowError, "long int too large to convert to int");
    return mpz_get_ui(self->n);
}

54 55 56 57
extern "C" unsigned long PyLong_AsUnsignedLong(PyObject* vv) {
    RELEASE_ASSERT(PyLong_Check(vv), "");
    BoxedLong* l = static_cast<BoxedLong*>(vv);

58 59 60 61 62
    try {
        return asUnsignedLong(l);
    } catch (Box* e) {
        abort();
    }
63 64
}

Marius Wachtler's avatar
Marius Wachtler committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
extern "C" long PyLong_AsLong(PyObject* vv) {
    RELEASE_ASSERT(PyLong_Check(vv), "");
    BoxedLong* l = static_cast<BoxedLong*>(vv);
    RELEASE_ASSERT(mpz_fits_slong_p(l->n), "");
    return mpz_get_si(l->n);
}

extern "C" long PyLong_AsLongAndOverflow(PyObject*, int*) {
    Py_FatalError("unimplemented");
}

extern "C" double PyLong_AsDouble(PyObject* vv) {
    RELEASE_ASSERT(PyLong_Check(vv), "");
    BoxedLong* l = static_cast<BoxedLong*>(vv);
    return mpz_get_d(l->n);
}

extern "C" PyObject* PyLong_FromDouble(double v) {
    Py_FatalError("unimplemented");
}

86 87 88 89 90 91
extern "C" PyObject* PyLong_FromUnsignedLong(unsigned long ival) {
    BoxedLong* rtn = new BoxedLong(long_cls);
    mpz_init_set_ui(rtn->n, ival);
    return rtn;
}

Marius Wachtler's avatar
Marius Wachtler committed
92 93 94 95
extern "C" double _PyLong_Frexp(PyLongObject* a, Py_ssize_t* e) {
    Py_FatalError("unimplemented");
}

96 97 98 99 100 101 102
extern "C" Box* createLong(const std::string* s) {
    BoxedLong* rtn = new BoxedLong(long_cls);
    int r = mpz_init_set_str(rtn->n, s->c_str(), 10);
    RELEASE_ASSERT(r == 0, "%d: '%s'", r, s->c_str());
    return rtn;
}

103 104 105 106 107 108
extern "C" BoxedLong* boxLong(int64_t n) {
    BoxedLong* rtn = new BoxedLong(long_cls);
    mpz_init_set_si(rtn->n, n);
    return rtn;
}

109 110 111 112 113 114 115 116 117
extern "C" Box* longNew(Box* _cls, Box* val) {
    if (!isSubclass(_cls->cls, type_cls))
        raiseExcHelper(TypeError, "long.__new__(X): X is not a type object (%s)", getTypeName(_cls)->c_str());

    BoxedClass* cls = static_cast<BoxedClass*>(_cls);
    if (!isSubclass(cls, long_cls))
        raiseExcHelper(TypeError, "long.__new__(%s): %s is not a subtype of long", getNameOfClass(cls)->c_str(),
                       getNameOfClass(cls)->c_str());

118 119
    assert(cls->tp_basicsize >= sizeof(BoxedInt));
    void* mem = gc_alloc(cls->tp_basicsize, gc::GCKind::PYTHON);
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
    BoxedLong* rtn = ::new (mem) BoxedLong(cls);
    initUserAttrs(rtn, cls);

    if (val->cls == int_cls) {
        mpz_init_set_si(rtn->n, static_cast<BoxedInt*>(val)->n);
    } else if (val->cls == str_cls) {
        const std::string& s = static_cast<BoxedString*>(val)->s;
        int r = mpz_init_set_str(rtn->n, s.c_str(), 10);
        RELEASE_ASSERT(r == 0, "");
    } else {
        fprintf(stderr, "TypeError: int() argument must be a string or a number, not '%s'\n",
                getTypeName(val)->c_str());
        raiseExcHelper(TypeError, "");
    }
    return rtn;
}

Box* longRepr(BoxedLong* v) {
    if (!isSubclass(v->cls, long_cls))
        raiseExcHelper(TypeError, "descriptor '__repr__' requires a 'long' object but received a '%s'",
                       getTypeName(v)->c_str());

    int space_required = mpz_sizeinbase(v->n, 10) + 2; // basic size
    space_required += 1;                               // 'L' suffix
    char* buf = (char*)malloc(space_required);
    mpz_get_str(buf, 10, v->n);
    strcat(buf, "L");

    auto rtn = new BoxedString(buf);
    free(buf);

    return rtn;
}

Box* longStr(BoxedLong* v) {
    if (!isSubclass(v->cls, long_cls))
        raiseExcHelper(TypeError, "descriptor '__str__' requires a 'long' object but received a '%s'",
                       getTypeName(v)->c_str());

    char* buf = mpz_get_str(NULL, 10, v->n);
    auto rtn = new BoxedString(buf);
    free(buf);

    return rtn;
}

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
Box* longNeg(BoxedLong* v1) {
    if (!isSubclass(v1->cls, long_cls))
        raiseExcHelper(TypeError, "descriptor '__neg__' requires a 'long' object but received a '%s'",
                       getTypeName(v1)->c_str());

    BoxedLong* r = new BoxedLong(long_cls);
    mpz_init(r->n);
    mpz_neg(r->n, v1->n);
    return r;
}

Box* longAdd(BoxedLong* v1, Box* _v2) {
    if (!isSubclass(v1->cls, long_cls))
        raiseExcHelper(TypeError, "descriptor '__add__' requires a 'long' object but received a '%s'",
                       getTypeName(v1)->c_str());

182 183
    if (isSubclass(_v2->cls, long_cls)) {
        BoxedLong* v2 = static_cast<BoxedLong*>(_v2);
184

185 186 187 188 189 190
        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init(r->n);
        mpz_add(r->n, v1->n, v2->n);
        return r;
    } else if (isSubclass(_v2->cls, int_cls)) {
        BoxedInt* v2 = static_cast<BoxedInt*>(_v2);
191

192 193 194 195 196 197 198 199 200 201
        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init(r->n);
        if (v2->n >= 0)
            mpz_add_ui(r->n, v1->n, v2->n);
        else
            mpz_sub_ui(r->n, v1->n, -v2->n);
        return r;
    } else {
        return NotImplemented;
    }
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
Box* longLshift(BoxedLong* v1, Box* _v2) {
    if (!isSubclass(v1->cls, long_cls))
        raiseExcHelper(TypeError, "descriptor '__lshift__' requires a 'long' object but received a '%s'",
                       getTypeName(v1)->c_str());

    if (isSubclass(_v2->cls, long_cls)) {
        BoxedLong* v2 = static_cast<BoxedLong*>(_v2);

        if (mpz_cmp_si(v2->n, 0) < 0)
            raiseExcHelper(ValueError, "negative shift count");

        uint64_t n = asUnsignedLong(v2);
        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init(r->n);
        mpz_mul_2exp(r->n, v1->n, n);
        return r;
    } else if (isSubclass(_v2->cls, int_cls)) {
        BoxedInt* v2 = static_cast<BoxedInt*>(_v2);
        if (v2->n < 0)
            raiseExcHelper(ValueError, "negative shift count");

        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init(r->n);
        mpz_mul_2exp(r->n, v1->n, v2->n);
        return r;
    } else {
        return NotImplemented;
    }
}

234 235 236 237 238
Box* longSub(BoxedLong* v1, Box* _v2) {
    if (!isSubclass(v1->cls, long_cls))
        raiseExcHelper(TypeError, "descriptor '__sub__' requires a 'long' object but received a '%s'",
                       getTypeName(v1)->c_str());

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    if (isSubclass(_v2->cls, long_cls)) {
        BoxedLong* v2 = static_cast<BoxedLong*>(_v2);

        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init(r->n);
        mpz_sub(r->n, v1->n, v2->n);
        return r;
    } else if (isSubclass(_v2->cls, int_cls)) {
        BoxedInt* v2 = static_cast<BoxedInt*>(_v2);

        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init(r->n);
        if (v2->n >= 0)
            mpz_sub_ui(r->n, v1->n, v2->n);
        else
            mpz_add_ui(r->n, v1->n, -v2->n);
        return r;
    } else {
257
        return NotImplemented;
258
    }
259 260
}

261 262 263 264 265 266 267 268
Box* longRsub(BoxedLong* v1, Box* _v2) {
    if (!isSubclass(v1->cls, long_cls))
        raiseExcHelper(TypeError, "descriptor '__rsub__' requires a 'long' object but received a '%s'",
                       getTypeName(v1)->c_str());

    return longAdd(static_cast<BoxedLong*>(longNeg(v1)), _v2);
}

269 270 271 272 273
Box* longMul(BoxedLong* v1, Box* _v2) {
    if (!isSubclass(v1->cls, long_cls))
        raiseExcHelper(TypeError, "descriptor '__mul__' requires a 'long' object but received a '%s'",
                       getTypeName(v1)->c_str());

274 275
    if (isSubclass(_v2->cls, long_cls)) {
        BoxedLong* v2 = static_cast<BoxedLong*>(_v2);
276

277 278 279 280 281 282
        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init(r->n);
        mpz_mul(r->n, v1->n, v2->n);
        return r;
    } else if (isSubclass(_v2->cls, int_cls)) {
        BoxedInt* v2 = static_cast<BoxedInt*>(_v2);
283

284 285 286 287 288 289 290
        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init(r->n);
        mpz_mul_si(r->n, v1->n, v2->n);
        return r;
    } else {
        return NotImplemented;
    }
291 292
}

293 294 295 296 297
Box* longDiv(BoxedLong* v1, Box* _v2) {
    if (!isSubclass(v1->cls, long_cls))
        raiseExcHelper(TypeError, "descriptor '__div__' requires a 'long' object but received a '%s'",
                       getTypeName(v1)->c_str());

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    if (isSubclass(_v2->cls, long_cls)) {
        BoxedLong* v2 = static_cast<BoxedLong*>(_v2);

        if (mpz_cmp_si(v2->n, 0) == 0)
            raiseExcHelper(ZeroDivisionError, "long division or modulo by zero");

        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init(r->n);
        mpz_fdiv_q(r->n, v1->n, v2->n);
        return r;
    } else if (isSubclass(_v2->cls, int_cls)) {
        BoxedInt* v2 = static_cast<BoxedInt*>(_v2);

        if (v2->n == 0)
            raiseExcHelper(ZeroDivisionError, "long division or modulo by zero");

        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init_set_si(r->n, v2->n);
        mpz_fdiv_q(r->n, v1->n, r->n);
        return r;
    } else {
319
        return NotImplemented;
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
extern "C" Box* longDivmod(BoxedLong* lhs, Box* _rhs) {
    if (!isSubclass(lhs->cls, long_cls))
        raiseExcHelper(TypeError, "descriptor '__div__' requires a 'long' object but received a '%s'",
                       getTypeName(lhs)->c_str());

    if (isSubclass(_rhs->cls, long_cls)) {
        BoxedLong* rhs = static_cast<BoxedLong*>(_rhs);

        if (mpz_cmp_si(rhs->n, 0) == 0)
            raiseExcHelper(ZeroDivisionError, "long division or modulo by zero");

        BoxedLong* q = new BoxedLong(long_cls);
        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init(q->n);
        mpz_init(r->n);
        mpz_fdiv_qr(q->n, r->n, lhs->n, rhs->n);
        return new BoxedTuple({ q, r });
    } else if (isSubclass(_rhs->cls, int_cls)) {
        BoxedInt* rhs = static_cast<BoxedInt*>(_rhs);

        if (rhs->n == 0)
            raiseExcHelper(ZeroDivisionError, "long division or modulo by zero");

        BoxedLong* q = new BoxedLong(long_cls);
        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init(q->n);
        mpz_init_set_si(r->n, rhs->n);
        mpz_fdiv_qr(q->n, r->n, lhs->n, r->n);
        return new BoxedTuple({ q, r });
    } else {
        return NotImplemented;
    }
}

357 358 359 360
Box* longRdiv(BoxedLong* v1, Box* _v2) {
    if (!isSubclass(v1->cls, long_cls))
        raiseExcHelper(TypeError, "descriptor '__div__' requires a 'long' object but received a '%s'",
                       getTypeName(v1)->c_str());
361

362
    if (mpz_cmp_si(v1->n, 0) == 0)
363 364
        raiseExcHelper(ZeroDivisionError, "long division or modulo by zero");

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    if (isSubclass(_v2->cls, long_cls)) {
        BoxedLong* v2 = static_cast<BoxedLong*>(_v2);

        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init(r->n);
        mpz_fdiv_q(r->n, v2->n, v1->n);
        return r;
    } else if (isSubclass(_v2->cls, int_cls)) {
        BoxedInt* v2 = static_cast<BoxedInt*>(_v2);

        BoxedLong* r = new BoxedLong(long_cls);
        mpz_init_set_si(r->n, v2->n);
        mpz_fdiv_q(r->n, r->n, v1->n);
        return r;
    } else {
        return NotImplemented;
    }
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
}

Box* longPow(BoxedLong* v1, Box* _v2) {
    if (!isSubclass(v1->cls, long_cls))
        raiseExcHelper(TypeError, "descriptor '__pow__' requires a 'long' object but received a '%s'",
                       getTypeName(v1)->c_str());

    if (!isSubclass(_v2->cls, long_cls))
        return NotImplemented;

    BoxedLong* v2 = static_cast<BoxedLong*>(_v2);

    RELEASE_ASSERT(mpz_sgn(v2->n) >= 0, "");
    RELEASE_ASSERT(mpz_fits_ulong_p(v2->n), "");
    uint64_t n2 = mpz_get_ui(v2->n);

    BoxedLong* r = new BoxedLong(long_cls);
    mpz_init(r->n);
    mpz_pow_ui(r->n, v1->n, n2);
    return r;
}

404 405 406 407 408 409 410 411 412 413
Box* longNonzero(BoxedLong* self) {
    if (!isSubclass(self->cls, long_cls))
        raiseExcHelper(TypeError, "descriptor '__pow__' requires a 'long' object but received a '%s'",
                       getTypeName(self)->c_str());

    if (mpz_cmp_si(self->n, 0) == 0)
        return False;
    return True;
}

414 415 416 417 418 419 420
void setupLong() {
    long_cls->giveAttr("__name__", boxStrConstant("long"));

    long_cls->giveAttr("__new__",
                       new BoxedFunction(boxRTFunction((void*)longNew, UNKNOWN, 2, 1, false, false), { boxInt(0) }));

    long_cls->giveAttr("__mul__", new BoxedFunction(boxRTFunction((void*)longMul, UNKNOWN, 2)));
421 422
    long_cls->giveAttr("__rmul__", long_cls->getattr("__mul__"));

423
    long_cls->giveAttr("__div__", new BoxedFunction(boxRTFunction((void*)longDiv, UNKNOWN, 2)));
424 425
    long_cls->giveAttr("__rdiv__", new BoxedFunction(boxRTFunction((void*)longRdiv, UNKNOWN, 2)));

426 427
    long_cls->giveAttr("__divmod__", new BoxedFunction(boxRTFunction((void*)longDivmod, UNKNOWN, 2)));

428
    long_cls->giveAttr("__sub__", new BoxedFunction(boxRTFunction((void*)longSub, UNKNOWN, 2)));
429 430
    long_cls->giveAttr("__rsub__", new BoxedFunction(boxRTFunction((void*)longRsub, UNKNOWN, 2)));

431
    long_cls->giveAttr("__add__", new BoxedFunction(boxRTFunction((void*)longAdd, UNKNOWN, 2)));
432
    long_cls->giveAttr("__radd__", long_cls->getattr("__add__"));
433

434 435
    long_cls->giveAttr("__lshift__", new BoxedFunction(boxRTFunction((void*)longLshift, UNKNOWN, 2)));

436 437 438
    long_cls->giveAttr("__repr__", new BoxedFunction(boxRTFunction((void*)longRepr, STR, 1)));
    long_cls->giveAttr("__str__", new BoxedFunction(boxRTFunction((void*)longStr, STR, 1)));

439 440
    long_cls->giveAttr("__nonzero__", new BoxedFunction(boxRTFunction((void*)longNonzero, BOXED_BOOL, 1)));

441 442 443
    long_cls->freeze();
}
}