01: /*
02: * ash.java
03: *
04: * Copyright (C) 2003 Peter Graves
05: * $Id: ash.java,v 1.6 2003/11/15 11:03:35 beedlem Exp $
06: *
07: * This program is free software; you can redistribute it and/or
08: * modify it under the terms of the GNU General Public License
09: * as published by the Free Software Foundation; either version 2
10: * of the License, or (at your option) any later version.
11: *
12: * This program is distributed in the hope that it will be useful,
13: * but WITHOUT ANY WARRANTY; without even the implied warranty of
14: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15: * GNU General Public License for more details.
16: *
17: * You should have received a copy of the GNU General Public License
18: * along with this program; if not, write to the Free Software
19: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20: */
21:
22: package org.armedbear.lisp;
23:
24: import java.math.BigInteger;
25:
26: // ### ash
27: // ash integer count => shifted-integer
28: public final class ash extends Primitive2 {
29: private ash() {
30: super ("ash");
31: }
32:
33: public LispObject execute(LispObject first, LispObject second)
34: throws ConditionThrowable {
35: if (first instanceof Fixnum && second instanceof Fixnum) {
36: int count = ((Fixnum) second).getValue();
37: if (count == 0)
38: return first;
39: long n = ((Fixnum) first).getValue();
40: if (n == 0)
41: return first;
42: if (count < -32) {
43: // Right shift.
44: return n >= 0 ? Fixnum.ZERO : Fixnum.MINUS_ONE;
45: }
46: if (count <= 32)
47: return number(count > 0 ? (n << count) : (n >> -count));
48: }
49: BigInteger n;
50: if (first instanceof Fixnum)
51: n = BigInteger.valueOf(((Fixnum) first).getValue());
52: else if (first instanceof Bignum)
53: n = ((Bignum) first).getValue();
54: else
55: throw new ConditionThrowable(
56: new TypeError(first, "integer"));
57: if (second instanceof Fixnum) {
58: int count = Fixnum.getInt(second);
59: if (count == 0)
60: return first;
61: // BigInteger.shiftLeft() succumbs to a stack overflow if count
62: // is Integer.MIN_VALUE, so...
63: if (count == Integer.MIN_VALUE)
64: return n.signum() >= 0 ? Fixnum.ZERO : Fixnum.MINUS_ONE;
65: return number(n.shiftLeft(count));
66: }
67: if (second instanceof Bignum) {
68: BigInteger count = ((Bignum) second).getValue();
69: if (count.signum() > 0)
70: throw new ConditionThrowable(new LispError(
71: "can't represent result of left shift"));
72: if (count.signum() < 0)
73: return n.signum() >= 0 ? Fixnum.ZERO : Fixnum.MINUS_ONE;
74: Debug.bug(); // Shouldn't happen.
75: }
76: throw new ConditionThrowable(new TypeError(second, "integer"));
77: }
78:
79: private static final ash ASH = new ash();
80: }
|