1 /* 2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package jdk.nashorn.internal.objects; 27 28 import static jdk.nashorn.internal.runtime.ECMAErrors.rangeError; 29 import static jdk.nashorn.internal.runtime.ECMAErrors.typeError; 30 import static jdk.nashorn.internal.runtime.JSType.isRepresentableAsInt; 31 import static jdk.nashorn.internal.runtime.JSType.isRepresentableAsLong; 32 import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; 33 import static jdk.nashorn.internal.lookup.Lookup.MH; 34 35 import java.lang.invoke.MethodHandle; 36 import java.lang.invoke.MethodHandles; 37 import java.lang.invoke.MethodType; 38 import java.text.NumberFormat; 39 import java.util.Locale; 40 import jdk.internal.dynalink.linker.GuardedInvocation; 41 import jdk.internal.dynalink.linker.LinkRequest; 42 import jdk.nashorn.internal.objects.annotations.Attribute; 43 import jdk.nashorn.internal.objects.annotations.Constructor; 44 import jdk.nashorn.internal.objects.annotations.Function; 45 import jdk.nashorn.internal.objects.annotations.Property; 46 import jdk.nashorn.internal.objects.annotations.ScriptClass; 47 import jdk.nashorn.internal.objects.annotations.Where; 48 import jdk.nashorn.internal.runtime.JSType; 49 import jdk.nashorn.internal.runtime.PropertyMap; 50 import jdk.nashorn.internal.runtime.ScriptObject; 51 import jdk.nashorn.internal.runtime.ScriptRuntime; 52 import jdk.nashorn.internal.runtime.linker.PrimitiveLookup; 53 54 /** 55 * ECMA 15.7 Number Objects. 56 * 57 */ 58 @ScriptClass("Number") 59 public final class NativeNumber extends ScriptObject { 60 61 // Method handle to create an object wrapper for a primitive number 62 private static final MethodHandle WRAPFILTER = findOwnMH("wrapFilter", MH.type(NativeNumber.class, Object.class)); 63 // Method handle to retrieve the Number prototype object 64 private static final MethodHandle PROTOFILTER = findOwnMH("protoFilter", MH.type(Object.class, Object.class)); 65 66 /** ECMA 15.7.3.2 largest positive finite value */ 67 @Property(attributes = Attribute.NON_ENUMERABLE_CONSTANT, where = Where.CONSTRUCTOR) 68 public static final double MAX_VALUE = Double.MAX_VALUE; 69 70 /** ECMA 15.7.3.3 smallest positive finite value */ 71 @Property(attributes = Attribute.NON_ENUMERABLE_CONSTANT, where = Where.CONSTRUCTOR) 72 public static final double MIN_VALUE = Double.MIN_VALUE; 73 74 /** ECMA 15.7.3.4 NaN */ 75 @Property(attributes = Attribute.NON_ENUMERABLE_CONSTANT, where = Where.CONSTRUCTOR) 76 public static final double NaN = Double.NaN; 77 78 /** ECMA 15.7.3.5 negative infinity */ 79 @Property(attributes = Attribute.NON_ENUMERABLE_CONSTANT, where = Where.CONSTRUCTOR) 80 public static final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY; 81 82 /** ECMA 15.7.3.5 positive infinity */ 83 @Property(attributes = Attribute.NON_ENUMERABLE_CONSTANT, where = Where.CONSTRUCTOR) 84 public static final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY; 85 86 private final double value; 87 private final boolean isInt; 88 private final boolean isLong; 89 90 // initialized by nasgen 91 private static PropertyMap $nasgenmap$; 92 93 static PropertyMap getInitialMap() { 94 return $nasgenmap$; 95 } 96 97 private NativeNumber(final double value, final ScriptObject proto, final PropertyMap map) { 98 super(proto, map); 99 this.value = value; 100 this.isInt = isRepresentableAsInt(value); 101 this.isLong = isRepresentableAsLong(value); 102 } 103 104 NativeNumber(final double value, final Global global) { 105 this(value, global.getNumberPrototype(), getInitialMap()); 106 } 107 108 private NativeNumber(final double value) { 109 this(value, Global.instance()); 110 } 111 112 113 @Override 114 public String safeToString() { 115 return "[Number " + toString() + "]"; 116 } 117 118 @Override 119 public String toString() { 120 return Double.toString(getValue()); 121 } 122 123 /** 124 * Get the value of this Number 125 * @return a {@code double} representing the Number value 126 */ 127 public double getValue() { 128 return doubleValue(); 129 } 130 131 /** 132 * Get the value of this Number 133 * @return a {@code double} representing the Number value 134 */ 135 public double doubleValue() { 136 return value; 137 } 138 139 /** 140 * Get the value of this Number as a {@code int} 141 * @return an {@code int} representing the Number value 142 * @throws ClassCastException If number is not representable as an {@code int} 143 */ 144 public int intValue() throws ClassCastException { 145 if (isInt) { 146 return (int)value; 147 } 148 throw new ClassCastException(); 149 } 150 151 /** 152 * Get the value of this Number as a {@code long} 153 * @return a {@code long} representing the Number value 154 * @throws ClassCastException If number is not representable as an {@code long} 155 */ 156 public long longValue() throws ClassCastException { 157 if (isLong) { 158 return (long)value; 159 } 160 throw new ClassCastException(); 161 } 162 163 @Override 164 public String getClassName() { 165 return "Number"; 166 } 167 168 /** 169 * ECMA 15.7.2 - The Number constructor 170 * 171 * @param newObj is this Number instantiated with the new operator 172 * @param self self reference 173 * @param args value of number 174 * @return the Number instance (internally represented as a {@code NativeNumber}) 175 */ 176 @Constructor(arity = 1) 177 public static Object constructor(final boolean newObj, final Object self, final Object... args) { 178 final double num = (args.length > 0) ? JSType.toNumber(args[0]) : 0.0; 179 180 return newObj? new NativeNumber(num) : num; 181 } 182 183 /** 184 * ECMA 15.7.4.5 Number.prototype.toFixed (fractionDigits) 185 * 186 * @param self self reference 187 * @param fractionDigits how many digits should be after the decimal point, 0 if undefined 188 * 189 * @return number in decimal fixed point notation 190 */ 191 @Function(attributes = Attribute.NOT_ENUMERABLE) 192 public static Object toFixed(final Object self, final Object fractionDigits) { 193 final int f = JSType.toInteger(fractionDigits); 194 if (f < 0 || f > 20) { 195 throw rangeError("invalid.fraction.digits", "toFixed"); 196 } 197 198 final double x = getNumberValue(self); 199 if (Double.isNaN(x)) { 200 return "NaN"; 201 } 202 203 if (Math.abs(x) >= 1e21) { 204 return JSType.toString(x); 205 } 206 207 final NumberFormat format = NumberFormat.getNumberInstance(Locale.US); 208 format.setMinimumFractionDigits(f); 209 format.setMaximumFractionDigits(f); 210 format.setGroupingUsed(false); 211 212 return format.format(x); 213 } 214 215 /** 216 * ECMA 15.7.4.6 Number.prototype.toExponential (fractionDigits) 217 * 218 * @param self self reference 219 * @param fractionDigits how many digital should be after the significand's decimal point. If undefined, use as many as necessary to uniquely specify number. 220 * 221 * @return number in decimal exponential notation 222 */ 223 @Function(attributes = Attribute.NOT_ENUMERABLE) 224 public static Object toExponential(final Object self, final Object fractionDigits) { 225 final double x = getNumberValue(self); 226 final boolean trimZeros = fractionDigits == UNDEFINED; 227 final int f = trimZeros ? 16 : JSType.toInteger(fractionDigits); 228 229 if (Double.isNaN(x)) { 230 return "NaN"; 231 } else if (Double.isInfinite(x)) { 232 return x > 0? "Infinity" : "-Infinity"; 233 } 234 235 if (fractionDigits != UNDEFINED && (f < 0 || f > 20)) { 236 throw rangeError("invalid.fraction.digits", "toExponential"); 237 } 238 239 final String res = String.format(Locale.US, "%1." + f + "e", x); 240 return fixExponent(res, trimZeros); 241 } 242 243 /** 244 * ECMA 15.7.4.7 Number.prototype.toPrecision (precision) 245 * 246 * @param self self reference 247 * @param precision use {@code precision - 1} digits after the significand's decimal point or call {@link NativeDate#toString} if undefined 248 * 249 * @return number in decimal exponentiation notation or decimal fixed notation depending on {@code precision} 250 */ 251 @Function(attributes = Attribute.NOT_ENUMERABLE) 252 public static Object toPrecision(final Object self, final Object precision) { 253 final double x = getNumberValue(self); 254 if (precision == UNDEFINED) { 255 return JSType.toString(x); 256 } 257 258 final int p = JSType.toInteger(precision); 259 if (Double.isNaN(x)) { 260 return "NaN"; 261 } else if (Double.isInfinite(x)) { 262 return x > 0? "Infinity" : "-Infinity"; 263 } 264 265 if (p < 1 || p > 21) { 266 throw rangeError("invalid.precision"); 267 } 268 269 // workaround for http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6469160 270 if (x == 0.0 && p <= 1) { 271 return "0"; 272 } 273 274 return fixExponent(String.format(Locale.US, "%." + p + "g", x), false); 275 } 276 277 /** 278 * ECMA 15.7.4.2 Number.prototype.toString ( [ radix ] ) 279 * 280 * @param self self reference 281 * @param radix radix to use for string conversion 282 * @return string representation of this Number in the given radix 283 */ 284 @Function(attributes = Attribute.NOT_ENUMERABLE) 285 public static Object toString(final Object self, final Object radix) { 286 if (radix != UNDEFINED) { 287 final int intRadix = JSType.toInteger(radix); 288 if (intRadix != 10) { 289 if (intRadix < 2 || intRadix > 36) { 290 throw rangeError("invalid.radix"); 291 } 292 return JSType.toString(getNumberValue(self), intRadix); 293 } 294 } 295 296 return JSType.toString(getNumberValue(self)); 297 } 298 299 /** 300 * ECMA 15.7.4.3 Number.prototype.toLocaleString() 301 * 302 * @param self self reference 303 * @return localized string for this Number 304 */ 305 @Function(attributes = Attribute.NOT_ENUMERABLE) 306 public static Object toLocaleString(final Object self) { 307 return JSType.toString(getNumberValue(self)); 308 } 309 310 311 /** 312 * ECMA 15.7.4.4 Number.prototype.valueOf ( ) 313 * 314 * @param self self reference 315 * @return boxed number value for this Number 316 */ 317 @Function(attributes = Attribute.NOT_ENUMERABLE) 318 public static Object valueOf(final Object self) { 319 return getNumberValue(self); 320 } 321 322 /** 323 * Lookup the appropriate method for an invoke dynamic call. 324 * @param request The link request 325 * @param receiver receiver of call 326 * @return Link to be invoked at call site. 327 */ 328 public static GuardedInvocation lookupPrimitive(final LinkRequest request, final Object receiver) { 329 return PrimitiveLookup.lookupPrimitive(request, Number.class, new NativeNumber(((Number)receiver).doubleValue()), WRAPFILTER, PROTOFILTER); 330 } 331 332 @SuppressWarnings("unused") 333 private static NativeNumber wrapFilter(final Object receiver) { 334 return new NativeNumber(((Number)receiver).doubleValue()); 335 } 336 337 @SuppressWarnings("unused") 338 private static Object protoFilter(final Object object) { 339 return Global.instance().getNumberPrototype(); 340 } 341 342 private static double getNumberValue(final Object self) { 343 if (self instanceof Number) { 344 return ((Number)self).doubleValue(); 345 } else if (self instanceof NativeNumber) { 346 return ((NativeNumber)self).getValue(); 347 } else if (self != null && self == Global.instance().getNumberPrototype()) { 348 return 0.0; 349 } else { 350 throw typeError("not.a.number", ScriptRuntime.safeToString(self)); 351 } 352 } 353 354 // Exponent of Java "e" or "E" formatter is always 2 digits and zero 355 // padded if needed (e+01, e+00, e+12 etc.) JS expects exponent to contain 356 // exact number of digits e+1, e+0, e+12 etc. Fix the exponent here. 357 // 358 // Additionally, if trimZeros is true, this cuts trailing zeros in the 359 // fraction part for calls to toExponential() with undefined fractionDigits 360 // argument. 361 private static String fixExponent(final String str, final boolean trimZeros) { 362 final int index = str.indexOf('e'); 363 if (index < 1) { 364 // no exponent, do nothing.. 365 return str; 366 } 367 368 // check if character after e+ or e- is 0 369 final int expPadding = str.charAt(index + 2) == '0' ? 3 : 2; 370 // check if there are any trailing zeroes we should remove 371 372 int fractionOffset = index; 373 if (trimZeros) { 374 assert fractionOffset > 0; 375 char c = str.charAt(fractionOffset - 1); 376 while (fractionOffset > 1 && (c == '0' || c == '.')) { 377 c = str.charAt(--fractionOffset - 1); 378 } 379 380 } 381 // if anything needs to be done compose a new string 382 if (fractionOffset < index || expPadding == 3) { 383 return str.substring(0, fractionOffset) 384 + str.substring(index, index + 2) 385 + str.substring(index + expPadding); 386 } 387 return str; 388 } 389 390 private static MethodHandle findOwnMH(final String name, final MethodType type) { 391 return MH.findStatic(MethodHandles.lookup(), NativeNumber.class, name, type); 392 } 393 }